我写简单的代码中插入一些数据MSSQL,但我得到了一些错误,如问题标题:当皈依的carchar转换失败
转换失败值“{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 [email protected]"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);
}
改用这种字符串操作的参数化的语句。这将处理。 –