我正在尝试将SQL数据库添加到我的项目中。我在使用显式路径时取得了成功,但是如果我使用相对路径|DataDirectory|\Data\Database.mdf
,则控制台似乎是在将数据写入数据库,但在数据库中查看服务器资源管理器后显示的不是数据。还有其他几个问题接近回答,但是在搜索Stack时,我无法找到有效或接近解决的答案。
修改 根据以下建议,我尝试了修复,但是,只是为了澄清。 程序似乎按预期连接并写入数据库,但是当我查看数据库结构时,没有创建表,也没有插入数据,即使程序运行没有错误
<connectionStrings>
<add name="rData"providerName="System.Data.SqlClient"connectionString="Data Source=(LocalDB)\MSSQLLocalDB; Initial Catalog=TestRecipeDatabase;AttachDbFilename=|DataDirectory|\Data\TestRecipeDatabase.mdf;Integrated Security=True" />
</connectionStrings>
public void connectToDB(string action)
{
var connectionString = ConfigurationManager.ConnectionStrings["rData"].ConnectionString;
Console.WriteLine(connectionString);
SqlConnection conn = new SqlConnection(connectionString);
if (action == "firstRun")
{
conn.Open();
// Creates the Database
try
{
using (SqlCommand createDBTable = new SqlCommand("" +
"CREATE TABLE RecipeStorage" +
"(" +
"rname char(50) NOT NULL, " +
"ringredients text, " +
"rdirections text" +
");", conn))
createDBTable.ExecuteNonQuery();
Console.WriteLine("Created Database");
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
System.Diagnostics.Trace.WriteLine(logTime + " " + e.Message);
}
// Sets the primary key to rname
try
{
using (SqlCommand setPrimaryKey = new SqlCommand("ALTER TABLE RecipeStorage ADD PRIMARY KEY (rname);", conn))
setPrimaryKey.ExecuteNonQuery();
Console.WriteLine("Set Primary Key to Recipe Name");
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
System.Diagnostics.Trace.WriteLine(logTime + " " +e.Message);
}
// Adds an initial recipe
try
{
using (SqlCommand firstLine = new SqlCommand("INSERT INTO RecipeStorage (rname, ringredients, rdirections) VALUES ('espresso', 'Hot water, coffee'," +
"'put coffee through espresso machine with hot water into cup, enjoy');", conn))
firstLine.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
System.Diagnostics.Trace.WriteLine(logTime + " " + e.Message);
}
conn.Close();
}
}
如上所述,当使用显式路径进行数据连接C:\User\User\Projects\CSharp\RecipeHandler\Data\TestRecipeDatabase.mdf
但是使用相对路径不起作用。理想情况下,我希望能够在任何显然没有数据库在同一个地方的计算机上运行