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

Uma*_*ved 9 c# database visual-studio-2008

我只是C#的初学者,所以我需要太多的帮助.现在的问题是我设计了一个窗口表单,其中有许多字段,如名字,姓氏,地址等.现在我想要做的是,当我填写表单并单击插入按钮时,所有信息都进入数据库.有谁知道这是怎么做到的吗?

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 19

您的查询中存在许多问题.
这是您的代码的修改版本

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);
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 列名称包含空格(应避免使用),因此您需要使用方括号
  • 您需要使用该using语句以确保将关闭连接并释放资源
  • 您将控件直接放在字符串中,但这不起作用
  • 您需要使用参数化查询来避免引用问题和sqlinjiection攻击
  • 无需使用DataAdapter进行简单的插入查询

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

编辑:如果你正在使用.NET Framework 1.1,那么你没有AddWithValue方法,所以用这些更改两个AddWithValue行

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码假定您的数据库列的类型为NVARCHAR,否则,请使用相应的SqlDbType枚举值.

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

  • @Umair Javed - 您为什么使用Visual Studio 2003.Visual Studio 2012 Express是100%免费的. (2认同)

Sid*_*med 5

使用参数化查询来防止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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Pil*_*anz 5

您应该更改代码以使用SqlParameters并使您的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!");
}
Run Code Online (Sandbox Code Playgroud)


Pao*_*sco -1

您应该使用文本框的内容构成命令:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
Run Code Online (Sandbox Code Playgroud)

当然,前提是您能够正确打开连接。

了解当前代码发生了什么会很有帮助。如果您在该消息框中显示一些错误,那么最好知道它的内容。

您还应该在实际运行命令之前验证输入(即确保它们不包含恶意代码......)。

  • 确实应该使用参数化查询而不是查询串联。 (3认同)