gpt4 book ai didi

c# - 通过C#在sql中插入数据

转载 作者:行者123 更新时间:2023-11-29 11:12:19 26 4
gpt4 key购买 nike

我已成功创建数据库连接,但现在插入数据时遇到问题。这是我的代码:

String Connection = null;
SqlConnection con;
SqlCommand cmd;
String sql = null;
Connection="Data Source=DELL\\SQLEXPRESS; initial Catalog= BSSE;Integrated Security=True";
con = new SqlConnection(Connection);
sql = "INSERT INTO Records (Roll_No,Name,Marks) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ");";
try
{
con.Open();
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}

最佳答案

首先,你的SQL语句不正确。您在值字段之间缺少单引号。稍后,您使用字符串连接构建 SQL 语句,这很危险,因为可能会暴露给 SQL Injection 。使用Parameterized Query相反。

try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Records (Roll_No,Name,Marks) VALUES (@rollNo, @Name, @Marks)", con);
cmd.Parameters.AddWithValue("@rollNo", textBox1.Text);
cmd.Parameters.AddWithValue("@Name", textBox2.Text);
cmd.Parameters.AddWithValue("@Marks", textBox3.Text);
cmd.ExecuteNonQuery();

MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}

关于c# - 通过C#在sql中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40354020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com