gpt4 book ai didi

c# - 如何使用C#语言在数据库中插入记录?

转载 作者:太空狗 更新时间:2023-10-29 17:30:38 25 4
gpt4 key购买 nike

我只是 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());
}
}

最佳答案

你的查询有很多问题。
这是您的代码的修改版本

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 因为它可能是错误的来源(见下面的链接)

除此之外,还有其他潜在的问题。如果用户没有在文本框控件中输入任何内容怎么办?在尝试插入之前,您是否对此做过任何检查?正如我所说,字段名称包含空格,这会给您的代码带来不便。尝试更改这些字段名称。

此代码假定您的数据库列是 NVARCHAR 类型,如果不是,则使用适当的 SqlDbType enum值(value)。

请计划尽快切换到更新版本的 NET Framework。 1.1 现在真的已经过时了。

并且,关于 AddWithValue 问题,本文解释了为什么我们应该避免它。 Can we stop using AddWithValue() already?

关于c# - 如何使用C#语言在数据库中插入记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12142806/

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