1.连接数据库
//server="地址",我用的是phpmyadmin,所以地址为localhost
using (MySqlConnection msconnection = new MySqlConnection("server=localhost;database=dbname;user=root;pwd=root"))
2.查找数据
MySqlCommand mscommand = new MySqlCommand("select * from person", msconnection);
using (MySqlDataReader reader = mscommand.ExecuteReader()) { }
3.读数据
while (reader.Read())
{
int Id = reader.GetInt32("Id");
string Name = reader.GetString("Name");
string Age = reader.GetString("Age");
}
4.当数据库连接不成功时
可以把代码try起来
//MySqlException ex里面,Exception 捕抓所有异常; MysqlException 捕抓数据库异常
namespace Demo
{
class Program
{
static void Main(string[] args)
{
try
{
using (MySqlConnection msconnection = new MySqlConnection("server=localhost;database=dbname;user=root;pwd=root"))
{
msconnection.Open();
//查找数据库里面的表
MySqlCommand mscommand = new MySqlCommand("select * from person", msconnection);
using (MySqlDataReader reader = mscommand.ExecuteReader())
{
//读取数据
while (reader.Read())
{
int Id = reader.GetInt32("Id");
string Name = reader.GetString("Name");
string Age = reader.GetString("Age");
}
}
}
}
catch (MySqlException ex)
{
throw ex;
}
return;
}