如何将一些值添加到数据库中

时间:2018-12-25 11:38:26

标签: c# sql-server database

我是C#的初学者,我编写了一个连接到数据库的代码,但它给我一个错误

我从一开始就做了所有事情,但是什么也没发生

private void btnSubmit_Click(object sender, EventArgs e) 
{
     string conString = "data source=DESKTOP-D5VFL9P; initial catalog = university; integrated security = True; MultipleActiveResultSets = True;";

     using (SqlConnection connection = new SqlConnection(conString)) 
     {
         connection.Open();

         using(SqlCommand command = new SqlCommand("INSERT INTO Persons (PersonID, LastName, FirstName, Age, City) VALUES (" + int.Parse(txtPersonID.Text) + ", '" +
    txtLastName.Text + "', '" + txtFirstName.Text + "' ," + int.Parse(txtAge.Text) + ", '" + txtCity.Text + "'", connection)) 
         {
             using(SqlDataReader reader = command.ExecuteReader()) 
             {
                  MessageBox.Show("Data inserted");

                  txtFirstName.Text = "";
                  txtLastName.Text = "";
                  txtPersonID.Text = "";
                  txtAge.Text = "";
                  txtCity.Text = "";
             }
         }
     }
 }

我想向数据库中添加一些值

2 个答案:

答案 0 :(得分:1)

城市后面应该有一个)。像txtCity.Text + "')"

答案 1 :(得分:1)

我不建议这样做,因为它肯定会为SQL Injection Attack打开一扇门,但请使用下面的字符串,这将在您的情况下起作用:

string cmdText =  "INSERT INTO Persons(PersonID,LastName,FirstName,Age,City)" +
                     " VALUES ('" + int.Parse(txtPersonID.Text) + "', " +
                               "'" + txtLastName.Text + "', " +
                               "'" + txtFirstName.Text + "' ,'" +
                               int.Parse(txtAge.Text) + "', '" +
                               txtCity.Text + "')"

我会做这样的事情:

using (SqlConnection conn = new SqlConnection(conString))
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = 
        "INSERT INTO Persons (PersonID,LastName,FirstName,Age,City) VALUES (@PersonID,@LastName,@FirstName,@Age,@City)";
    cmd.Parameters.AddWithValue("@PersonID", int.Parse(txtPersonID.Text));
    cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
    cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("@Age", int.Parse(txtAge.Text));
    cmd.Parameters.AddWithValue("@City", txtCity.Text);
    cmd.Connection = conn;
    conn.Open();
    int rowsAffected = cmd.ExecuteNonQuery();
    if(rowsAffected > 0)
    {
        MessageBox.Show("Data inserted");
    }
    else
    {
       MessageBox.Show("Failed");
    }
    conn.Close();
}