C# – 連接Mysql

此程式需使用 MySql.Data.dll
需於編寫時 加入」References」(參考)
下載點: 下載點

using MySql.Data.MySqlClient;

MySqlConnection conn;
MySqlCommand command;
String connStr;
String host = "host";
String dbUser = "username";
String dbPassword = "password";
String dbName = "dbname";

connStr = "server=" + host + ";uid=" + dbUser + ";pwd=" + dbPassword + ";database=" + dbName + "; convert zero datetime=True";

conn = new MySqlConnection(connStr);

try
{
	conn.Open();
}
catch (MySqlException ex)
{
	switch (ex.Number)
	{
		case 0:
			MessageBox.Show("connect db failed.");
			break;
		case 1042:
			MessageBox.Show("ip incorrect.");
			break;
		case 1045:
			MessageBox.Show("username or password incorrect.");
			break;
		default:
			MessageBox.Show("error");
			break;
	}

	return;
}

//以下為Select table例子
String sql = "SELECT `id`,DATE_FORMAT(`time`,'%Y-%m-%d %H:%i:%s') FROM `user`";
command = new MySqlCommand(sql, conn);

MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
	try
	{
		String id = reader.GetString(0);
		String time = reader.GetString(1);

	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.ToString());
	}
}

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部