转换carchar值' {0}'转换失败到数据类型int

时间:2015-05-23 11:51:58

标签: c# sql-server

我编写简单的代码将一些数据插入到MSSQL中,但我得到一些错误,如问题标题:

  

转换carchar值' {0}&#39>时转换失败到数据类型   中间体

这是我的dbc类来进行连接

 public dbc()
    {
        conn = new SqlConnection();
        conn.ConnectionString = connectionString;
        cmd = new SqlCommand();
        cmd.Connection = conn;
        da = new SqlDataAdapter();
        dt = new DataTable();
    }
    void connect()
    {
        if (conn.State == ConnectionState.Closed)
            conn.Open();
    }
    void disconnect()
    {
        if (conn.State == ConnectionState.Open)
            conn.Close();
    }

    public string runQuery(string SQL)
    {
        string result = "";
        cmd.CommandText = SQL;
        connect();
        try
        {
            cmd.ExecuteNonQuery();
            result = "null";
        }
        catch(Exception ex)
        {
            result = ex.Message.ToString();

        }
        disconnect();
        return result;
    }
    public DataTable retQuery(string SQL)
    {   
        connect();
        try
        {
            cmd.CommandText = SQL;
            da.SelectCommand.Connection = conn;
            da.SelectCommand.CommandText = cmd.CommandText;
            cmd.ExecuteReader();
            da.Fill(dt);
            return dt;
        }
        catch
        {
            return null;
        }
        finally
        {
            disconnect();
        }
    }
}

我确实插入了这样的操作:

string SQL =@"INSERT INTO tbl_emp (empid,empname,empmaried,empclass,empdate) VALUES('{0}','{1}','{2}','{3}','{4}')";
string.Format(SQL,Convert.ToInt32(textBox1.Text),textBox2.Text.ToString(),
            comboBox1.SelectedItem,comboBox2.SelectedItem,
            dateTimePicker1.Value.ToString());
dbc db = new dbc();
var sign = db.runQuery(SQL);
if ( sign == "null")
{
    MessageBox.Show("Done!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show(sign.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

1 个答案:

答案 0 :(得分:1)

您的问题是因为'使用empid等非字符字段, 对于表格的非字符字段,请使用{0}代替'{0}'

并在下一行之前添加SQL =,如下所示:

SQL = string.Format(SQL,Convert.ToInt32(textBox1.Text),textBox2.Text.ToString(),
        comboBox1.SelectedItem,comboBox2.SelectedItem,
        dateTimePicker1.Value.ToString());