3

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

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
4

3 回答 3

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)"
于 2012-10-24T05:06:50.007 回答
0

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

这条线

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

应该是这样的

"INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "','" & code & "')"
于 2012-10-24T05:17:44.097 回答
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;

    }
于 2013-11-26T20:15:14.367 回答