我们说我的查询结果如下:
ID NAME Phone
---- ---- -----
1 John 123456
2 John 125678
3 John 345678
4 Abby 456789
5 Abby 567890
我想只返回一个名称的单行实例:John,其中的电话号码类似于' 12%'。
在c#中,我编写了这种语法来获取PersonName变量作为查询的结果。
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
connection.Close();
我不知道我的代码有什么问题,但PersonName返回null。我做错了什么?
答案 0 :(得分:1)
我们必须在这里遗漏别的东西。根据您提供的内容尝试以下代码示例:
try {
MySqlConnection connection = new MySqlConnection("SERVER=localhost;DATABASE=testdb;UID=root;PASSWORD=;");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
finally {
connection.Close();
}
我有一种感觉,由于某种原因,对.Open()的调用失败,错误被其他地方吞没。试试上面的内容,让我知道你发现了什么。
答案 1 :(得分:0)
执行此操作:将 (string)command.ExecuteScalar();
更改为 Convert.ToString(command.ExecuteScalar());
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand 命令 = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = Convert.ToString(command.ExecuteScalar());
connection.Close();