我是visual studio 2010和mysql的新手。我正在创建一个可以添加员工的表单。但是,当我单击add按钮时,出现了一个错误,指出“输入字符串的格式不正确”。
这是屏幕截图:
代码:
private void button_adduser_Click(object sender, EventArgs e)
{
string MyConString = "SERVER=localhost;" + "DATABASE=timekeeping;" + "UID=root;" + "PASSWORD=admin;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
command.Connection = connection;
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
connection.Open();
using (MySqlCommand com = connection.CreateCommand())
{
command.CommandText = "insert into users(fname, mname, lname, position, contactnumber, emailadd, birthday, username, password) values(@fname, @mname, @lname, @position, @contactnumber, @emailadd, @birthday, @username, @password)";
command.Parameters.Add(new MySqlParameter("@fname", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@mname", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@lname", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@position", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@contactnumber", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@emailadd", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@birthday", SqlDbType.DateTime));
command.Parameters.Add(new MySqlParameter("@username", SqlDbType.VarChar));
command.Parameters.Add(new MySqlParameter("@password", SqlDbType.VarChar));
command.Parameters["@fname"].Value = addfname.Text;
command.Parameters["@mname"].Value = addmname.Text;
command.Parameters["@lname"].Value = addlname.Text;
command.Parameters["@position"].Value = addposition.Text;
command.Parameters["@contactnumber"].Value = addcontact.Text;
command.Parameters["@emailadd"].Value = addemail.Text;
command.Parameters["@birthday"].Value = addbday.Text;
command.Parameters["@username"].Value = addusername.Text;
command.Parameters["@password"].Value = addpassword.Text;
command.ExecuteNonQuery();
}
}
}
最佳答案
错误就在这里:
command.Parameters["@birthday"].Value = addbday.Text;
addbday.text不在非日期时间字段中。
即使你已经宣布这是约会时间:
command.Parameters.Add(new MySqlParameter("@birthday", SqlDbType.DateTime));
将违规行重写为:
command.Parameters["@birthday"].Value = Convert.ToDateTime(addbday.Text);