简体   繁体   中英

How to Insert data into a MSSQL table using C#

I'm trying to using INSERT to write some data to a MSSQL Database table. I believe my SQL string is correct but I'm getting an error message when I run command.ExecuteScaler(); I've attached the error message in a screen shot. It states I'm using incorrect syntax but I'm not getting any compiler errors. I'm assuming I'm just doing something wrong.

CODE:

using (SqlConnection connection = new SqlConnection(SQLHelper.CnnCal("CQDB")))
{
    connection.Open();
    String insert = @"INSERT INTO Skills(SkillName, SkillNumber, SkillLastUpdated, SkillServer) VALUES(" + skills.SkillName + "," + skills.SkillNumber + "," + skills.LastUpdated + "," + skills.CallServer +")";
    SqlCommand command = new SqlCommand(insert, connection);
    command.ExecuteScalar();
    connection.Close();
}

Error Message from exception pop up

Question: What is the proper way of inserting data into a MSSQL database table?

You should be using Parameters to prevent SQL Injection.

The below code takes care of that:

var query = "INSERT INTO Skills(SkillName, SkillNumber, SkillLastUpdated, SkillServer) 
             VALUES (@SkillName, @SkillNumber, @SkillLastUpdated, @SkillServer)";

using (SqlConnection connection = new SqlConnection(SQLHelper.CnnCal("CQDB")))
{
    using(SqlCommand cmd = new SqlCommand(query, connection))
    {
        // add parameters and their values
        cmd.Parameters.Add(new SqlParameter("SkillName", skills.SkillName ));
        cmd.Parameters.Add(new SqlParameter("SkillNumber", skills.SkillNumber ));
        cmd.Parameters.Add(new SqlParameter("SkillLastUpdated", skills.LastUpdated ));
        cmd.Parameters.Add(new SqlParameter("SkillServer", skills.CallServer

        cn.Open();
        cmd.ExecuteNonQuery();
    }    
}

you forgot to set the connection property for the command object: command.Connection = connection; and:

command.CommandType = CommandType.Text;
command.CommandText = your_sql_query;

See: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM