转换字符值'{0}'到数据类型int

本文关键字:数据类型 int 字符 转换 | 更新日期: 2023-09-27 17:50:38

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

将字符值"{0}"转换为数据类型时,转换失败int。

这是我的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);
}

转换字符值'{0}'到数据类型int

您的问题是因为使用'为您的非字符字段,如empid,对于表中的非字符字段,使用{0}而不是'{0}'

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

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