在WinForms应用程序中呈现MySQL中的数据
本文关键字:MySQL 数据 WinForms 应用程序 | 更新日期: 2023-09-27 18:12:52
我有一个应用程序,我试图创建,但我卡住了。
我试图访问网站的MySQL查询在我的代码。
现在我只是试着测试它,以确保它能工作,但我没有运气。
我想我只是忽略了一些简单的东西,但我不确定。任何帮助吗?
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public List<string>[] list = new List<string>[1];
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
database = "XXX";
uid = "XXX";
password = "XXX";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database
+ ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//this will open the connection to MySql
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
//if there is a problem connecting, display one of the following connections
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact Admin");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//if the connection fails to connect to MySql server, the client will close the connection.
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Select statement
public List<string>[] Select()
{
int firstNumber = 2058;
**string query = "USE `db_order` SELECT `order_id` FROM `order_address` WHERE order_id=2058";**
//create a list to store the results
list[0] = new List<string>(0);
//Open's connection
if (this.OpenConnection() == true)
{
//creates a command from the query.
MySqlCommand cmd = new MySqlCommand(query, connection);
//creates a data reader, and executes the command.
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list[0].Add(dataReader["order_id"] + "");
}
//close Data Reader
dataReader.Close();
this.CloseConnection();
//returns list to be displayed
return list;
}
else
{
return list;
}
}
}
这是第二个类(我去掉了任何不是问题的一部分):
public partial class Form1
{
private void InitializeComponent()
{
// CustName
//
this.CustName.AutoSize = true;
this.CustName.Location = new System.Drawing.Point(200, 30);
this.CustName.Name = "CustName";
this.CustName.Size = new System.Drawing.Size(137, 13);
this.CustName.TabIndex = 0;
this.CustName.Text = "Customer''s name goes here" + new DBConnect().list[0];
}
#endregion
}
更新
你像这样从你的DataReader
中添加列表
list[0].Add(dataReader["order_id"] + "");
所以,这意味着你有一个multi-dimensional
(确切地说是二维)数组的列表。因此,要访问你必须像Select()[0][0]
一样,检查下面:
DBConnect() DBCon = new DBConnect();
this.Custname.Text = DBCon.Select()[0].Count>0 ? "Customer''s name goes here" +DBCon.Select()[0][0].ToString() : "No Customer to show";