繁体   English   中英

如何将Google输入的数字字符串转换为整数作为存储到MySql DB中?

[英]How to convert Google Input typed number String into integer as Store into MySql DB?

我想将google输入类型的数字存储到其列为Integer的数据库中。 当我想将其转换为整数时,出现错误,提示输入字符串格式不正确,该如何解决此问题?

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()请在使用前阅读有关该函数的信息

尝试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(); }你应该考虑的一些可能的问题是:

  • 如果cmd1没有返回任何内容,因此将空白值传递给@num怎么办?
  • cmd.ExecuteNonQuery()并非要返回任何内容,因此将其分配给对象可能不是最好的主意。 相反,您可以将其放在try / catch中。 例如, 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()); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM