代码可以正常编译,没有错误或警告,但数据库不会更改。我的意思是所做的更改不会保存到数据库中。
我编写了以下方法:
private void Test2()
{
connection = new SqlConnection();
string Conn = @"Data Source=(LocalDB)\MSSQLLocalDB;"
+ @"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
// string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(Conn);
try
{
string SQL = "UPDATE Primuser SET Following = @Following WHERE Insta = @Insta";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("@Following", "123");
sqlCommand.Parameters.AddWithValue("@Insta", "hgd");
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
,并且在此代码中,结果大于0。
private void Test2()
{
connection = new SqlConnection();
connection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;"
+ @"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Primuser";
command.Connection = connection;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset, "Primuser");
foreach (DataRow row in dataset.Tables["Primuser"].Rows)
{
if (row["Insta"].ToString() == "1495")
{
row["Following"] = "1024";
}
}
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
try
{
var result = adapter.Update(dataset, "Primuser");
if (result > 0)
MessageBox.Show("Update Successful.");
else
MessageBox.Show("Update Failed.");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
,但数据库未更改。没有错误,其他查询正在运行。我可以插入,删除或选择,但是更新不起作用。