我试图从Microsoft Visual Studio 2013中的数据库中检索数据。无论我是否已经能够连接到数据库,我都完全迷失了,我不知道如何使用c#检索数据,因为我对c#完全不熟悉。 我也不确定在connectDB()方法之前或之后我应该在哪里放置静态void main方法语句。
private void connectDB()
{
// server = "172.20.129.159";
database = "eyetracker";
server = "localhost";
// uid = "ogamaaccess";
// password = "ogama";
uid = "root";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
c = new MySqlConnection(connectionString);
Console.WriteLine("Connected to database");
}
private bool OpenConnection()
{
try
{
c.Open();
Console.WriteLine("Connection Opened.");
return true;
}
catch (MySqlException)
{
return false;
}
答案 0 :(得分:0)
您需要安装MySql NET Connector,它提供连接到MySQL数据库的相应位。
安装提供程序后,您需要添加对MySql.Data.Dll的引用,并在代码中添加相应的using语句
using MySql.Data.MySqlClient;
您还需要更改可在here.
中找到的连接字符串连接代码应该看起来与此接近:
private void Login() // login method
{
string connectString = @"uid=<UserID>;password=<Password>;
server=<IPorDomainNameOfDatabase>;
database=<DatabaseNameOnServer>;";;
using(MySqlConnection cnn = new MySqlConnection(connectString))
{
try
{
cnn.Open();
}
catch (Exception e)
{
.....
}
}
}
完整代码看起来像这样(命令应根据您要检索的数据进行编辑):
MySqlConnection connect = new MySqlConnection(connectString);
MySqlCommand command = connect.CreateCommand();
command.CommandText = "Select <VALUE> from <TABLE> order by <ID> desc limit <0,1>;";
//Command to get query needed value from DataBase
connect.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
var result = reader.GetString(0);
}
注意:我强烈建议您将connect.Open();
放入TryCatch语句,因为有很多事情可能会出错并且您的程序会崩溃。