在调用Read()INSERT之前无法尝试访问字段

时间:2012-10-24 04:55:41

标签: mysql vb.net

我正在尝试使用此代码检查系统是否已存在具有此值的字段

Dim adap As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM client WHERE code ='"+ TxtCode.Text +"'"
                Dim comand As New MySqlCommand()
                comand.Connection = con
                comand.CommandText = sqlquery
                adap.SelectCommand = comand
                Dim data As MySqlDataReader
                data = comando2.ExecuteReader()
                leitor.Read()
                If (data(3).ToString) = code Then
                    MsgBox("already exists", MsgBoxStyle.Information)
                    TxtCode.ResetText()
                    TxtCode.Focus()
                Else
                    Console.WriteLine(insert("INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "')"))
                    con.Close()
                End If

3 个答案:

答案 0 :(得分:0)

您致电leitor.Read(),但未在代码中致电data.Read()

此外,由于您的查询为SELECT * FROM client WHERE code = '1234',因此无需检查data(3) == code。如果存在记录,data.Read()将为真

If data.Read() Then
   MsgBox("already exists", MsgBoxStyle.Information)
   TxtCode.ResetText()
   TxtCode.Focus()
Else
   Console.WriteLine(insert("INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "')"))
   con.Close()
End If

使用参数而不是连接

也是一种很好的做法
  Dim sqlquery = "SELECT * FROM client WHERE code = @code"
  ...

  command.Parameters("@code", code); //this is safer

和插入

 "INSERT INTO client (name, tel, code) VALUES (@name, @tel)"

答案 1 :(得分:0)

您正在插入两个值,但为输入

指定了3个值

这一行

"INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "')"

应该是

"INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "','" & code & "')"

答案 2 :(得分:0)

这是我的解决方案:

 public bool isPhoneInfo(string hashPhone)
    {
        using (MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(_connStrng))
        {
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "CALL SP_IS_PHONEINFO(?p_hashInfo);";
            cmd.Parameters.AddWithValue("?p_hashInfo", hashPhone);

            try
            {
                conn.Open();
                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                while (dr.Read())
                {
                    string hashPhoneInfo = dr["hashPhone"].ToString();
                    if (!hashPhoneInfo.Equals(string.Empty))
                        return true;
                }
            }
            catch (MySqlException e)
            {
                System.Diagnostics.Debug.WriteLine("Error in : "+e);
            }
        }
        return false;

    }