我正在尝试解决此问题。我只是试图访问数据库并借助C#插入一些值
我尝试过的东西(有效)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
插入了新行,一切正常,现在我尝试使用变量插入一行:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id, @username, @password, @email)"; command.Parameters.AddWithValue("@id","abc") command.Parameters.AddWithValue("@username","abc") command.Parameters.AddWithValue("@password","abc") command.Parameters.AddWithValue("@email","abc") command.ExecuteNonQuery();
无效,未插入任何值。我又尝试了一件事
command.Parameters.AddWithValue("@id", SqlDbType.NChar); command.Parameters["@id"].Value = "abc"; command.Parameters.AddWithValue("@username", SqlDbType.NChar); command.Parameters["@username"].Value = "abc"; command.Parameters.AddWithValue("@password", SqlDbType.NChar); command.Parameters["@password"].Value = "abc"; command.Parameters.AddWithValue("@email", SqlDbType.NChar); command.Parameters["@email"].Value = "abc"; command.ExecuteNonQuery();
谁能告诉我我做错了吗?
亲切的问候
编辑:
在另一行中,我正在创建一个新的SQL命令
var cmd = new SqlCommand(query, connection);
仍然无法正常工作,我在上面的代码中找不到任何错误。
我假设您已连接到数据库,并且无法使用c#执行插入参数。
您没有在查询中添加参数。它应该看起来像:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)"; SqlCommand command = new SqlCommand(query, db.Connection); command.Parameters.Add("@id","abc"); command.Parameters.Add("@username","abc"); command.Parameters.Add("@password","abc"); command.Parameters.Add("@email","abc"); command.ExecuteNonQuery();
更新:
using(SqlConnection connection = new SqlConnection(_connectionString)) { String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)"; using(SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@id", "abc"); command.Parameters.AddWithValue("@username", "abc"); command.Parameters.AddWithValue("@password", "abc"); command.Parameters.AddWithValue("@email", "abc"); connection.Open(); int result = command.ExecuteNonQuery(); // Check Error if(result < 0) Console.WriteLine("Error inserting data into Database!"); } }