填充数据表时的FormatException

时间:2012-11-01 13:05:02

标签: c# asp.net mysql

在这行代码中总会引发FormatException,它说:

  

输入字符串的格式不正确。

以下是代码:

private void btnRegister_Click(object sender, EventArgs e)
{
    try
    {
        con.Open();
        MySqlCommand cmd = new MySqlCommand();
        cmd.Connection = con;
        cmd.CommandType =CommandType.Text;

        cmd.CommandText = "SELECT DriverID, FirstName, LastName FROM Driver WHERE FirstName = @FirstName AND LastName = @LastName or DriverID = @DriverID";
        cmd.Parameters.AddWithValue("@FirstName", MySqlDbType.VarChar).Value = txtEmployeeFN.Text;
        cmd.Parameters.AddWithValue("@LastName", MySqlDbType.VarChar).Value = txtEmployeeLN.Text;
        cmd.Parameters.AddWithValue("@DriverID", MySqlDbType.VarChar).Value = txtEmpID.Text;
        MySqlDataAdapter adp = new MySqlDataAdapter();
        adp.SelectCommand = cmd;

        DataTable Mydt = new DataTable();

        adp.Fill(Mydt); <===Here is the line where the exception is

        con.Close();

4 个答案:

答案 0 :(得分:1)

您不需要AddWithValue和.Value。使用:

        cmd.Parameters.AddWithValue("@FirstName", txtEmployeeFN.Text);
        cmd.Parameters.AddWithValue("@LastName", txtEmployeeLN.Text);
        cmd.Parameters.AddWithValue("@DriverID", txtEmpID.Text);

如果要强制执行类型,请使用Add

    cmd.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = txtEmployeeFN.Text;
    cmd.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = txtEmployeeLN.Text;
    cmd.Parameters.Add("@DriverID", MySqlDbType.VarChar).Value = txtEmpID.Text;

顺便说一下,检查以确保你的表字段都是VarChars。

答案 1 :(得分:0)

像这样使用AddWithValue

cmd.CommandText = "SELECT DriverID, FirstName, LastName FROM Driver WHERE FirstName = @FirstName AND LastName = @LastName or DriverID = @DriverID";
cmd.Parameters.AddWithValue("@FirstName", txtEmployeeFN.Text);
cmd.Parameters.AddWithValue("@LastName", txtEmployeeLN.Text);
cmd.Parameters.AddWithValue("@DriverID", txtEmpID.Text);

但请注意,如果您使用 ODBC ,则无法使用命名参数。你必须使用位置参数。

答案 2 :(得分:0)

我看到一些可能存在问题的事情:

SELECT DriverID, FirstName, LastName 
FROM Driver 
WHERE FirstName = @FirstName 
    AND LastName = @LastName 
    or DriverID = @DriverID
  1. DriverID是一个整数吗?如果是这样,参数类型应该是整数,而不是VarChar
  2. 如果@DriverID不是字符串格式的有效整数值,则可能引发此异常
  3. 您的where子句可能无效。您应该对您OR的承包进行分组:

  4.   WHERE (FirstName = @FirstName 
        AND LastName = @LastName)
        or DriverID = @DriverID
    

答案 3 :(得分:0)

你不需要添加这样的参数,你应该试试这个: -

cmd.CommandText = string.format(
"SELECT DriverID, FirstName, LastName 
FROM Driver WHERE FirstName = {0} AND LastName = {1} OR DriverID = {2}", 
txtEmployeeFN.Text.trim(),txtEmployeeLN.Text.trim(), txtEmpID.Text.trim());

如果输入字符串仍然是不正确的格式,那么您有语法问题。

为什么不在Visual Studio中打开服务器资源管理器,在您创建的数据连接上打开创建查询,模仿您在代码中执行的操作。

Visual Studio将向您显示需要在代码中使用的SQL查询文本。