我想在" Navn"中插入值排和" Varenr"当我点击按钮时,数据库表中的一行。我有以下代码:
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
{
try
{
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
string col1 = textBox2.Text;
string col2 = textBox3.Text;
//generate sql statement
cm.CommandText = "INSERT INTO ProduktTable (Navn,Varenr) VALUES (@col1,@col2)";
//add some SqlParameters
SqlParameter sp_add_col1 = new SqlParameter();
sp_add_col1.ParameterName = "@col1";
//data type in sqlserver
sp_add_col1.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col1.Size = 20;
sp_add_col1.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col1);
//in your insert into statement, there are how many parameter, you must write the number of parameter
SqlParameter sp_add_col2 = new SqlParameter();
sp_add_col2.ParameterName = "@col2";
//data type in sqlserver
sp_add_col2.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col2.Size = 20;
sp_add_col2.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col2);
//open the DB to execute sql
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
但不幸的是,我的数据表仍然是空的:
我在ExecuteNonQuery函数上设置了一个断点,当按下按钮时它被触发:
我的表格定义:
答案 0 :(得分:2)
你的连接字符串导致了这个:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"
|DataDirectory|
此方法中正在更新的数据库位于您的应用数据目录中,而您尝试从中检索数据的数据库位于项目文件夹中...
|DataDirectory|
是一个替换字符串,表示数据库的路径。 DataDirectory
还可以轻松共享项目以及部署应用程序。对于我的电脑,我的应用数据目录是:
C:\Users\MyUserName\AppData\...
如果您浏览到此位置,然后转到以下文件夹
...\Local\Apps\2.0\Data
您将能够找到您的特定应用程序目录,可能与您的程序集名称一起存储,或者当您去那里时会发现一些哈希,您会发现数据库正在更新中。此连接字符串最适合部署。
你也可以试试这个:
如果您注意到Server Explorer正在检测我的PC上的所有数据库,并且您可以注意到有几个MINDMUSCLE.MDF
文件但所有文件都位于不同的路径,这是因为{{1}中有一个文件目录,一个在我的DEBUG
目录中,一个在我的PROJECT
目录中。以数字开头的那些存储在我的APP DATA
目录中......如果您选择相应的数据库文件,然后针对它运行APP DATA
查询,您将获得数据。
我前段时间做过tutorial。可能它会帮助你:
答案 1 :(得分:1)
检查ExecuteNonQuery返回的值。它应返回一个int,其中包含受SQL语句影响的记录数。
如果它返回的值不是0,那么你知道某个记录正在某处插入。在关闭连接之前,对表运行SQL查询以选择所有记录,并查看它们是否通过代码返回。
SELECT * FROM ProduktTable
如果您获得了一些记录,那么您可能需要通过IDE仔细检查您正在查看的数据库以及通过代码插入记录的数据库。您可能有两个不同的数据库,并且在插入另一个数据库时查询一个数据库。
这些是我要帮助缩小问题范围的步骤,听起来像我以前可能做过的事情。我希望它有所帮助!