2015-05-23 150 views
0

我写简单的代码中插入一些数据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); 
} 
+2

改用这种字符串操作的参数化的语句。这将处理。 –

回答

1

你的问题是因为使用'你喜欢非字符字段empid, 使用{0}而不是'{0}'表示表格的非字符字段。

而且也是下一行之前添加一个SQL =这样的:

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

我这样做了,但我得到了一些错误:0附近的语法错误。 – Frd

+0

谢谢,它的工作就像一个魅力,是的,我忘了SQL = ... – Frd