我正在尝试在我的C#应用程序中运行SELECT查询,但实际上我确实陷入了困境。我如何从MySql数据库中选择一些东西?
我目前的代码如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Helpful
{
class database_connector
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
// Constructor
public database_connector()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "xxx";
database = "xxx";
uid = "xxx";
password = "xxx";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator.");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Select statement
public void user_check(string username, string password)
{
string query = "SELECT * FROM swear_tool WHERE username =" + username;
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Close();
this.CloseConnection();
}
}
}
}
但我怎么能看到这实际上是否有效?因为如果我尝试在消息框中显示结果,它将返回,无法转换为字符串。
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
MessageBox.Show(dataReader);
dataReader.Close();
this.CloseConnection();
}
答案 0 :(得分:1)
您需要知道数据库中需要哪个字段。
使用像SELECT Id, Name FROM swear_tool WHERE username =" + username
这样的SQL和用于检索Name
字段的代码。
指数0 = Id
索引1 =名称< - GetString(1)
if (dataReader.HasRows) {
while (dataReader.Read()) {
Console.WriteLine("{0}", dataReader.GetString(1) );
}
} else {
Console.WriteLine("No rows.");
}