I want to store google input typed number into database whose column is Integer. when i want to convert it to integer it gives me error said that Input string was not in correct formate how to solve this Problem?
MySqlConnection con = new MySqlConnection("Server=syits03-pc;Database=Demo;Uid=root;Pwd=kbabu4668;CharSet=utf8;");
con.Open();
MySqlCommand cmd = new MySqlCommand("insert into tblnew(str,num,numstr) values(@str,@num,@numstr)", con);
cmd.Parameters.AddWithValue("@str", textBox1.Text);
MySqlCommand cmd1= new MySqlCommand("Select str from tblnew where id=1",con);
cmd.Parameters.AddWithValue("@num", Convert.ToInt32(cmd1.ExecuteScalar().ToString()));
cmd.Parameters.AddWithValue("@numstr", textBox3.Text);
object obj= cmd.ExecuteNonQuery();
con.Close();
if (obj != null)
{
MessageBox.Show("Inserted");
}
看起来您的cmd.executescalar有时可能返回null,有时它会由tostring()函数转换为“”,这可能是错误原因,如果您不确定输入的输入是否正确,则可以始终尝试使用int .TryParse()请在使用前阅读有关该函数的信息
Try this using (SqlConnection con = new SqlConnection("Server = syits03 - pc; Database = Demo; Uid = root; Pwd = kbabu4668; CharSet = utf8; ")) { SqlCommand cmd1 = new SqlCommand("Select top 1 str from tblnew where id -1", con); string num = cmd1.ExecuteScalar().ToString(); string cmdText = string.Concat("insert into tblnew(str, num, numstr) values(", textBox1.Text, ",", num, ",", textBox3.Text, ")"); SqlCommand cmd = new SqlCommand(cmdText, con); cmd.ExecuteNonQuery(); }
using (SqlConnection con = new SqlConnection("Server = syits03 - pc; Database = Demo; Uid = root; Pwd = kbabu4668; CharSet = utf8; ")) { SqlCommand cmd1 = new SqlCommand("Select top 1 str from tblnew where id -1", con); string num = cmd1.ExecuteScalar().ToString(); string cmdText = string.Concat("insert into tblnew(str, num, numstr) values(", textBox1.Text, ",", num, ",", textBox3.Text, ")"); SqlCommand cmd = new SqlCommand(cmdText, con); cmd.ExecuteNonQuery(); }
using (SqlConnection con = new SqlConnection("Server = syits03 - pc; Database = Demo; Uid = root; Pwd = kbabu4668; CharSet = utf8; ")) { SqlCommand cmd1 = new SqlCommand("Select top 1 str from tblnew where id -1", con); string num = cmd1.ExecuteScalar().ToString(); string cmdText = string.Concat("insert into tblnew(str, num, numstr) values(", textBox1.Text, ",", num, ",", textBox3.Text, ")"); SqlCommand cmd = new SqlCommand(cmdText, con); cmd.ExecuteNonQuery(); }
Some possible issues you should think of are:
try { cmd.ExecuteNonQuery(); MessageBox.Show("Inserted"); } catch (Exception ex) { MessageBox.Show("Stored Proc failed with error: " + ex.ToString()); }
try { cmd.ExecuteNonQuery(); MessageBox.Show("Inserted"); } catch (Exception ex) { MessageBox.Show("Stored Proc failed with error: " + ex.ToString()); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.