以下是我要实现的代码:
public static void InsertData(string sqlStatement)
{
try
{
//string strConn = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
//string StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6); // remove file:\\
//string connectionString = @"Data Source=Database1.sdf";
//string connectionString = @"Data Source = |DataDirectory|\Database1.sdf";
//string connectionString = @"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
//string connectionString = string.Format("Data Source={0}; Persist Security Info=False;", Path.Combine(Application.StartupPath, "Database1.sdf"));
//THIS ONE ACTUALLY WORKS!!!!!!!!!!!! :
//string connectionString = @"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
string connectionString = Properties.Settings.Default.Database1ConnectionString;
SqlCeConnection sqlceCon = new SqlCeConnection(connectionString);
sqlceCon.Open();
SqlCeCommand sqlCeCom = new SqlCeCommand(sqlStatement, sqlceCon);
sqlCeCom.ExecuteNonQuery();
sqlCeCom.Dispose();
sqlceCon.Close();
}
catch (Exception e)
{
}
}
您可以看到所有注释的连接字符串,以查看我尝试过的内容。奇怪的是,我可以在另一个方法(SELECT语句,而不是INSERT INTO语句)中使用以下连接字符串,它从数据中获取单个值,并且工作正常。
string connectionString = @"Data Source = |DataDirectory|\Database1.sdf";
我已经直接测试了查询,就像评论所说的那样,静态路径确实有效,因此告诉我我的查询是好的。但当然,我需要一些相对于发布和多开发人员开发的东西。
我尝试过的大多数连接字符串都允许try块完成而没有错误,但数据没有插入。
有什么建议吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
/*If your solution is web application, make sure Database1.sdf location path is under the
* App_Data folder
* Web.Config <add name="LocalDB" connectionString="Data Source=|DataDirectory|\Database1.sdf"/>
*/
protected string ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["LocalDB"].ToString();
}
}
/*
* or you can use try absolute path as connectionstring
* modify your directory path as PhysicalApplicationPath result
*/
public string BaseDirConnString
{
get
{
if ((HttpContext.Current == null) || (HttpContext.Current.Request == null))
{
throw new ApplicationException("...");
}
return @"Data Source=" + HttpContext.Current.Request.PhysicalApplicationPath + "VIN Decoder\\Database1.sdf";
}
}
protected SqlCeConnection SqlCeConnection
{
get
{
var connection = new SqlCeConnection(BaseDirConnString);
connection.Open();
return connection;
}
}