一聚教程网:一个值得你收藏的教程网站

热门教程

c#连接mysql数据库的方法实例

时间:2022-11-14 23:37:43 编辑:袖梨 来源:一聚教程网

c#连接mysql教程数据库教程的方法实例

程序代码:

using MySQLDriverCS; // 建立数据库连接
MySQLConnection DBConn;
DBConn = new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open(); // 执行查询语句
MySQLCommand DBComm;
DBComm = new MySQLCommand("select Host,User from user",DBConn); // 读取数据MySQLDataReader DBReader = DBComm.ExecuteReaderEx(); // 显示数据
try{while (DBReader.Read()){
Console.WriteLine("Host = {0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1));}}
finally
{DBReader.Close();DBConn.Close();
} //关闭数据库连接DBConn.Close();

实例

static void Main(string[] args)
{
string sqlstr = "select * from manavatar";
MySQLConnection DBConn = new MySQLConnection(new MySQLConnectionString("192.168.0.13", "flashdata", "root", "root", 3306).AsString);
DBConn.Open();
//MySQLDataAdapter myadap = new MySQLDataAdapter(sqlstr, conn);
MySQLCommand DBComm = new MySQLCommand(sqlstr,DBConn);
MySQLDataReader DBReader = DBComm.ExecuteReaderEx(); //DBComm.ExecuteReaderEx();
MySQLDataAdapter DTAdapter = new MySQLDataAdapter(sqlstr,DBConn);

DataSet myDataSet = new DataSet();
DTAdapter.Fill(myDataSet,"manavatar");


try
{
while (DBReader.Read())
{
//Console.WriteLine("11");
Console.WriteLine("DBReader:{0},tttddddd:{1},tt {2}",DBReader.GetString(0), DBReader.GetString(1),DBReader.GetString(3));
}
Console.WriteLine("0000");
}
catch (Exception e)
{
Console.WriteLine("读入失败!"+e.ToString());
}
finally
{
Console.WriteLine("DBReader关闭");
Console.WriteLine("DBConn关闭");
DBReader.Close();
//DBConn.Close();
}

for (int i = 0; i < myDataSet.Tables["manavatar"].Rows.Count; i++)
{
Console.WriteLine("{0}",myDataSet.Tables["manavatar"].Rows[2]["user"]);
}


}

这是一个简单的例子。
在这里有个问题:dataset如果没设主键的话,可能会引起一些对数库操作的问题,比如会造成updata出现错误

热门栏目