1. 使用控制台程序
2.net工程和MySQL链接
1导入dll
Program.cs
static void Main(string[] args)
{
//等待用户的输入,或ctrl+f5程序运行到最后也会暂停
Console.Read();
}
2建立连接
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database = gamebd;user=root;password=root";
MySqlConnection c = new MySqlConnection(connectStr);
try
{
//试着运行这里的代码
c.Open();
Console.WriteLine("已经建立连接");
}
catch(Exception e)
{
//如果报错执行这里
Console.WriteLine(e.ToString());
}
finally
{
c.Clone();
}
//等待用户的输入,或ctrl+f5程序运行到最后也会暂停
Console.Read();
}
3执行数据库命令MySQLDataReader
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database = gamebd;user=root;password=root";
MySqlConnection c = new MySqlConnection(connectStr);
try
{
//试着运行这里的代码
c.Open();
string sql = "select*from users";
MySqlCommand cmd = new MySqlCommand(sql, c);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString() + reader[3].ToString());
reader.Read();
Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString() + reader[3].ToString());
Console.WriteLine("已经建立连接");
}
catch(Exception e)
{
//如果报错执行这里
Console.WriteLine(e.ToString());
}
finally
{
c.Clone();
}
//等待用户的输入,或ctrl+f5程序运行到最后也会暂停
Console.Read();
}
4对数据进行插入操作
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database = gamebd;user=root;password=root";
MySqlConnection c = new MySqlConnection(connectStr);
try
{
//试着运行这里的代码
//Read(c);
//Insert(c);
}
catch(Exception e)
{
//如果报错执行这里
Console.WriteLine(e.ToString());
}
finally
{
c.Clone();
}
//等待用户的输入,或ctrl+f5程序运行到最后也会暂停
Console.Read();
}
private static void Insert(MySqlConnection c)
{
c.Open();
string sql = "INSERT INTO `gamebd`.`users` (`username`, `password`, `registerdate`) VALUES ('ee', 'ee', '2018-07-02');";
MySqlCommand cmd = new MySqlCommand(sql, c);
var result = cmd.ExecuteNonQuery();
}
private static void Read(MySqlConnection c)
{
c.Open();
string sql = "select*from users";
MySqlCommand cmd = new MySqlCommand(sql, c);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString() + reader[3].ToString());
reader.Read();
Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString() + reader[3].ToString());
Console.WriteLine("已经建立连接");
}
结果