如何使用C#语言在数据库中插入记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12142806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert Records in Database using C# language?
提问by Umair Javed
I am just a begginer on C# so i need too much help. Now the problem is that i have designed a windows form in which there are many fields like first name, last name, address etc. Now i want to do is that when i fill the form and click insert button all the information goes into database. Does anyone know how to do that?
我只是 C# 的初学者,所以我需要太多帮助。现在的问题是我设计了一个 windows 窗体,其中有很多字段,如名字、姓氏、地址等。现在我想做的是,当我填写表格并单击插入按钮时,所有信息都会进入数据库。有谁知道这是怎么做到的吗?
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());
}
}
回答by Paolo Tedesco
You should form the command with the contents of the textboxes:
您应该使用文本框的内容形成命令:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
当然,前提是您设法正确打开连接。
It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
了解您当前的代码发生了什么会很有帮助。如果您在该消息框中显示一些错误,那么知道它在说什么会很棒。
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).
您还应该在实际运行命令之前验证输入(即确保它们不包含恶意代码......)。
回答by Steve
There are many problems in your query.
This is a modified version of your code
您的查询有很多问题。
这是您的代码的修改版本
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);
}
}
- The column names contain spaces (this should be avoided) thus you need square brackets around them
- You need to use the
usingstatement to be sure that the connection will be closed and resources released - You put the controls directly in the string, but this don't work
- You need to use a parametrized query to avoid quoting problems and sqlinjiection attacks
- No need to use a DataAdapter for a simple insert query
- Do not use AddWithValue because it could be a source of bugs (See link below)
- 列名包含空格(应该避免),因此您需要在它们周围加上方括号
- 您需要使用该
using语句来确保将关闭连接并释放资源 - 您将控件直接放在字符串中,但这不起作用
- 您需要使用参数化查询来避免引用问题和 sqlinjiection 攻击
- 无需使用 DataAdapter 进行简单的插入查询
- 不要使用 AddWithValue 因为它可能是错误的来源(见下面的链接)
Apart from this, there are other potential problems. What if the user doesn't input anything in the textbox controls? Do you have done any checking on this before trying to insert? As I have said the fields names contain spaces and this will cause inconveniences in your code. Try to change those field names.
除此之外,还有其他潜在的问题。如果用户没有在文本框控件中输入任何内容怎么办?在尝试插入之前,您是否对此进行了任何检查?正如我所说,字段名称包含空格,这会给您的代码带来不便。尝试更改这些字段名称。
This code assumes that your database columns are of type NVARCHAR, if not, then use the appropriate SqlDbType enumvalue.
此代码假定您的数据库列的类型为 NVARCHAR,如果不是,则使用适当的SqlDbType 枚举值。
Please plan to switch to a more recent version of NET Framework as soon as possible. The 1.1 is really obsolete now.
请计划尽快切换到更新版本的 NET Framework。1.1现在真的过时了。
And, about AddWithValue problems, this article explain why we should avoid it. Can we stop using AddWithValue() already?
并且,关于 AddWithValue 问题,本文解释了为什么我们应该避免它。我们可以停止使用 AddWithValue() 了吗?
回答by SidAhmed
Use a parameterized query to prevent Sql injections (secutity problem)
使用参数化查询防止Sql注入(安全问题)
Use the using statement so the connection will be closed and resources will be disposed.
使用 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();
}
}
回答by Jaime Yule
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name)is not a valid field. It should be FirstName or First_Name. It may be your problem.
(Firt Name)不是有效字段。它应该是 FirstName 或 First_Name。这可能是你的问题。
回答by Pilgerstorfer Franz
You should change your code to make use of SqlParametersand adapt your insert statement to the following
您应该更改代码以使用SqlParameters并将插入语句调整为以下内容
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!");
}
回答by user12703142
You should form the command with the contents of the textboxes:
您应该使用文本框的内容形成命令:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text +
"," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
当然,前提是您设法正确打开连接。
It would be helpful to know what is happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
了解您当前的代码发生了什么会很有帮助。如果您在该消息框中显示一些错误,那么知道它在说什么会很棒。
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code).
您还应该在实际运行命令之前验证输入(即确保它们不包含恶意代码)。

