每次运行都会出现System.Data.SqlClient.SqlException","附近有语法错误

private void InsertInfo() { Random rd = new Random(); int iDown = 100000; int iUp = 999999; int num = Convert.ToInt32(rd.Next(iDown, iUp)); int NumPeo = Convert.ToInt32(this.nudNum.Value); DateTime date = this.dtFromtime.Value; dbh = new DBHelper(); dbh.OpenConn(); string sql = "insert into UserFlyInfo values('"+No+"','"+Company+"',"+FromAddress+","+Goaddress+",'"+Fromtime+"','"+Gotime+"','"+Price+"',"+NumPeo+",'"+date+"','"+num+"')"; SqlCommand command = new SqlCommand(sql, dbh.Conn); int cancle = command.ExecuteNonQuery(); if(cancle>0) { MessageBox.Show("预订成功! 订单编号:" + num); } else { MessageBox.Show("预定失败!","操作提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } }

调试的时候 int cancle = command.ExecuteNonQuery(); 是这句出现问题 ,老是找不出问题

断点跟踪command.ExecuteNonQuery();这句.看它的返回值是什么.

不为-1即为数据插入成功.否则代表数据无法被插入,同时重新断点,从当前方法的第一句开始跟踪.

逐步检查每一句是否都有正常的返回值.

如果语法没有错误.检查是不是拼写问题,

最好不要用拼接字符串的方式来拼接SQL语句,一方面性能不好,另一方面可能会产生SQL注射问题.再要命的就是拼接的长了,自己都能看晕.

用SqlCommand.Parameters 属性来提交SQL语句并拼接参数.

另外再补充一句,不要把SQL语句中的需要传值的参数给隐藏掉.这点很不好.很容易在写SQL语句时造成错误.不要偷懒或者耍小聪明用简化写法.请完整编写SQL语句.


MSDN中的参考方法如下:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored 
    // in an xml column. 
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-19
1数据库是否连接
2插入语句是否正确
相似回答