如何使用C#将数据插入MSSQL表

时间:2017-06-27 15:30:00

标签: c# sql-server

我尝试使用INSERT将一些数据写入MSSQL数据库表。我相信我的SQL字符串是正确的但我在运行command.ExecuteScaler()时收到错误消息。我在屏幕截图中附加了错误消息。它声明我使用了不正确的语法,但我没有得到任何编译器错误。 我假设我做错了。

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

问题: 将数据插入MSSQL数据库表的正确方法是什么?

2 个答案:

答案 0 :(得分:5)

您应该使用Parameters来阻止SQL注入。

以下代码负责:

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

答案 1 :(得分:-2)

您忘记为命令对象设置连接属性:command.Connection = connection;

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

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