C# 如何使用C语言在数据库中插入记录?
我只是个乞讨者,所以我需要太多的帮助。现在的问题是,我设计了一个windows窗体,其中有许多字段,如名字、姓氏、地址等。现在我想做的是,当我填写窗体并单击“插入”按钮时,所有信息都进入数据库。有人知道怎么做吗C# 如何使用C语言在数据库中插入记录?,c#,database,visual-studio-2008,C#,Database,Visual Studio 2008,我只是个乞讨者,所以我需要太多的帮助。现在的问题是,我设计了一个windows窗体,其中有许多字段,如名字、姓氏、地址等。现在我想做的是,当我填写窗体并单击“插入”按钮时,所有信息都进入数据库。有人知道怎么做吗 private void button1_Click(object sender, System.EventArgs e) { string connetionString = null; SqlConnection cnn ; SqlDataAdapter ad
private void button1_Click(object sender, System.EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
cnn = new SqlConnection(connetionString);
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
try
{
cnn.Open();
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
您应使用文本框的内容形成命令:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text +
"," + textbox3.Text+ ")";
当然,前提是您能够正确打开连接
了解当前代码的情况会很有帮助。如果您在该消息框中显示了一些错误,那么了解它的含义将是非常棒的
您还应该在实际运行命令之前验证输入(即确保它们不包含恶意代码…。您的查询中存在许多问题。
这是您的代码的修改版本
string connetionString = null;
string sql = null;
// All the info required to reach your db. See connectionstrings.com
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// Prepare a proper parameterized query
sql = "insert into Main ([Firt Name], [Last Name]) values(@first,@last)";
// Create the connection (and be sure to dispose it at the end)
using(SqlConnection cnn = new SqlConnection(connetionString))
{
try
{
// Open the connection to the database.
// This is the first critical step in the process.
// If we cannot reach the db then we have connectivity problems
cnn.Open();
// Prepare the command to be executed on the db
using(SqlCommand cmd = new SqlCommand(sql, cnn))
{
// Create and set the parameters values
cmd.Parameters.Add("@first", SqlDbType.NVarChar).Value = textbox2.text;
cmd.Parameters.Add("@last", SqlDbType.NVarChar).Value = textbox3.text;
// Let's ask the db to execute the query
int rowsAdded = cmd.ExecuteNonQuery();
if(rowsAdded > 0)
MessageBox.Show ("Row inserted!!" + );
else
// Well this should never really happen
MessageBox.Show ("No row inserted");
}
}
catch(Exception ex)
{
// We should log the error somewhere,
// for this example let's just show a message
MessageBox.Show("ERROR:" + ex.Message);
}
}
- 列名包含空格(应避免使用空格),因此 他们周围需要方括号
- 您需要使用
语句来确保连接 将关闭并释放资源using
- 您将控件直接放入字符串中,但这不起作用
- 您需要使用参数化查询来避免引用问题和 SQLInjection攻击
- 对于简单的插入查询,不需要使用DataAdapter
- 不要使用AddWithValue,因为它可能是bug的来源(请参阅下面的链接)
另外,关于AddWithValue问题,本文解释了为什么我们应该避免它 使用参数化查询防止Sql注入(安全问题) 使用using语句,以便关闭连接并释放资源
using(var connection = new SqlConnection("connectionString"))
{
connection.Open();
var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
cmd.ExecuteNonQuery();
}
}
(第一个名称)不是有效字段。它应该是FirstName或First_Name。这可能是您的问题。您应该更改代码以使用insert语句,并使其适应以下情况
string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// [ ] required as your fields contain spaces!!
string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";
using (SqlConnection cnn = new SqlConnection(connetionString))
{
cnn.Open();
SqlCommand insCmd = new SqlCommand(insStmt, cnn);
// use sqlParameters to prevent sql injection!
insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
int affectedRows = insCmd.ExecuteNonQuery();
MessageBox.Show (affectedRows + " rows inserted!");
}
您应使用文本框的内容形成命令:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text +
"," + textbox3.Text+ ")";
当然,前提是您能够正确打开连接
了解当前代码发生了什么情况会很有帮助。如果您在该消息框中显示了一些错误,那么了解它的含义将是非常棒的
您还应该在实际运行命令之前验证输入(即确保它们不包含恶意代码)。现在添加了什么?因为它看起来像是“textbox2.text”和“textbox3.text”可能什么都没有。我用这个来检查,但都是徒劳的。你的数据库中有一列叫做“Firt Name”和“Last Name”吗?他们之间真的有空格吗?我必须投票表决这个问题,因为这个查询无法成功运行,这表明用户完全没有调试,因为该命令从未实际运行。确实应该使用参数化查询而不是查询连接。C:\Users\umair.javed\Documents\Visual Studio Projects\Air Handling\Form1.cs(278):“System.Data.SqlClient.SqlParameterCollection”不包含“AddWithValue”的定义。我将把答案更改为与框架版本1.1兼容的代码。我正在等待您的答案。由于
SqlCommand
实现了IDisposable
,因此使用它的块应该被using包围(SqlCommand cmd=newsqlcommand(sql,cnn))
@Umair Javed-为什么要使用Visual Studio 2003。Visual Studio 2012 Express是100%免费的。