0

所以我有一个包含以下列的表:ID、名称、地址等。

我一直在做一些研究,但我无法找到正确的关键字来找出我想做的事情。我希望能够获取名称值(可以说......“John Doe”肯定已经在数据库中......)并检索它的 ID(来自 int MySQL 值 ID)。

我遇到了以下代码,但我似乎无法弄清楚如何扩展其限制以满足我的需求。

  connection2.Open();
        cmd.ExecuteNonQuery();
        try
        {
            MySqlDataReader myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                Console.WriteLine(myReader.GetString(myReader.GetOrdinal("id")));
            }
            myReader.Close();
        }
        finally
        {
            connection2.Close();
        } 

这也是我力所能及的办法。

        MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";");
        string query = @"SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
        MySqlCommand cmd = new MySqlCommand(query, connection2);
4

2 回答 2

1

您应该用 sql 参数替换硬编码参数,但这里是您需要在此处执行的操作的一般概念。使用您当前的 sql 查询。

    MySqlConnection sqlConn = new MySqlConnection();
    MySqlCommand sqlCmd = new MySqlCommand();
    string sSql = "SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
    sqlConn.ConnectionString = "Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";";
    sqlCmd.CommandText = sSql;
    sqlCmd.CommandType = CommandType.Text;
    sqlConn.Open();
    sqlCmd.Connection = sqlConn;
    MySqlDataReader reader = sqlCmd.ExecuteReader();
    List<string> results = new List<string>();

    while (reader.Read())
    {

        results.Add((reader["id"].ToString());

    }

    reader.Close();
    sqlConn.Close();

请记住,您可以将阅读器结果添加到字符串,添加到上面的列表中,无论您想用它做什么。

于 2013-07-14T04:00:27.880 回答
0

这是如何 id en name pawe

        clsMySQL.sql_con.Open();
        string id = ID;
       
        sql = "SELECT *FROM test";
        cmd = new MySqlCommand(sql, clsMySQL.sql_con);
        
        
        sql_cmd = new MySqlCommand(sql, clsMySQL.sql_con);
        MySqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            id = dr["id"].ToString();
            user = dr["user_name"].ToString();
            pass = dr["password"].ToString();
             
            if (name.Text == user && passw.Text == pass)
            {
                string depart = id;
                Hide();

                MessageBox.Show("it works");
                // Then show the main form
                cracker form = new cracker(name.Text);
                form.sid = depart;
                form.Show();
                MessageBox.Show(ID);
            }
        }
        else
        {
            MessageBox.Show("Invalid Login please check username and password");
        }
        clsMySQL.sql_con.Close();
    }
于 2021-10-08T15:10:16.697 回答