CR9*_*191 0 c# sql-server visual-studio-2013
由于我的第二个查询错误,我在将评论插入我的评论表时遇到了麻烦.我继续把我的消息框(调试)读取为(se7en,57547,4)甚至0如果我使用查询而不是(24,57547,4),因为当我输入电影时,它将被转换为电影ID号,以便用作不同表的int.我的目标是阅读为(24,57547,4),以便插入我的桌子.
private void InsertReview_Click(object sender, EventArgs e)
{
string filename, connectionInfo;
SqlConnection db;
this.listBox1.Items.Clear();
filename = "netflix.mdf";
connectionInfo = String.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\{0};Integrated Security=True;", filename);
db = new SqlConnection(connectionInfo);
db.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = db;
string moviename = this.textBox1.Text;
moviename = moviename.Replace("'", "''");
cmd.CommandText = string.Format(
@"SELECT MovieID FROM Movies
where MovieName = '{0}';", moviename);
object result = cmd.ExecuteScalar();
int id = System.Convert.ToInt32(result);
this.listBox1.Items.Add(id); //debugging to make sure it converted right
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = db;
cmd2.CommandText = //the 2nd query, the issue im posting here
string.Format(
@"INSERT INTO Reviews (MovieID, UserID, Rating)
VALUES({0});", id, this.textBox1.Text);
MessageBox.Show(cmd2.CommandText); //debugging
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
db.Close();
//this.listBox1.Items.Add("Movie Review inserted successfully!");
}
Run Code Online (Sandbox Code Playgroud)
在你的string.Format中:
cmd2.CommandText = //the 2nd query, the issue im posting here
string.Format(
@"INSERT INTO Reviews (MovieID, UserID, Rating)
VALUES({0});", id, this.textBox1.Text);
Run Code Online (Sandbox Code Playgroud)
您只有一个格式项{0},但是您要传递两个参数以插入到字符串中.而您正试图在表格中插入3列数据.我不确定UserID和Rating的存储位置/方式,但您的代码应该更像:
cmd2.CommandText = //the 2nd query, the issue im posting here
string.Format(
@"INSERT INTO Reviews (MovieID, UserID, Rating)
VALUES({0}, {1}, '{2}');", id, userId, rating);
Run Code Online (Sandbox Code Playgroud)
这是做动态SQL的一种非常糟糕的方法.
您应该参数化查询,如下所示:
cmd2.CommandText = //the 2nd query, the issue im posting here
@"INSERT INTO Reviews (MovieID, UserID, Rating)
VALUES(@MovieId, @UserId, @Rating);");
cmd2.Parameters.AddWithValue("@MovieId", id);
cmd2.Parameters.AddWithValue("@UserId", userId);
cmd2.Parameters.AddWithValue("@Rating", rating);
Run Code Online (Sandbox Code Playgroud)