c winform mysql类_C#连接MySQL数据库操作类
首先需要安裝MySQL Connector Net 6.8.3
然后在項目中引用MySQL Connector,如下圖所示
C#連接MySQL的操作類代碼如下:public?class?MySQLHelper
{
private?string?db_host?=?"localhost";?//數據庫服務器
private?string?db_port?=?"3306";?//數據庫端口號
private?string?db_user?=?"root";?//數據庫用戶
private?string?db_pass?=?"123456";?//數據庫密碼
private?string?db_name?=?"myblog";?//數據庫名
private?MySqlConnection?dbconn;
public?MySQLHelper()
{
//do?nothing
}
~MySQLHelper()
{
this.CloseDBconn();
}
//連接數據庫
public?void?OpenDBconn()
{
this.dbconn?=?new?MySqlConnection();
this.dbconn.ConnectionString?=?"server="?+?this.db_host?+?";uid="?+?this.db_user?+?";pwd="?+?this.db_pass?+?";database="?+?this.db_name?+?";";
if?(this.db_port.Length?>?0)
{
this.dbconn.ConnectionString?+=?";port="?+?this.db_port;
}
try
{
this.dbconn.Open();
}
catch?(MySqlException?ex)
{
string?message?=?"無法連接數據庫:?"+?ex.Message;
string?caption?=?"系統提示";
MessageBoxButtons?buttons?=?MessageBoxButtons.OK;
DialogResult?result?=?MessageBox.Show(message,?caption,?buttons);
Environment.Exit(0);
}
}
//關閉數據庫
public?void?CloseDBconn()
{
if?(this.dbconn?!=?null)
{
this.dbconn.Close();
}
}
//查詢數據
public?MySqlDataReader?query(string?sqltext)
{
MySqlCommand?cmd?=?new?MySqlCommand();
cmd.Connection?=?this.dbconn;
cmd.CommandType?=?CommandType.Text;
cmd.CommandText?=?sqltext;
MySqlDataReader?reader?=?cmd.ExecuteReader();
return?reader;
}
//更新數據
public?int?execute(string?sqltext)
{
MySqlCommand?cmd?=?new?MySqlCommand();
cmd.Connection?=?this.dbconn;
cmd.CommandType?=?CommandType.Text;
cmd.CommandText?=?sqltext;
int?result?=?cmd.ExecuteNonQuery();
return?result;
}
}
使用方法(查詢數據):this.dbhelper?=?new?MySQLHelper();
this.dbhelper.OpenDBconn();
string?sqltext?=?"s.e.l.e.c.t?*?from?blog?w.h.e.r.e?id=123?order?by?id?asc?limit?0,1";
MySqlDataReader?reader?=?this.dbhelper.query(sqltext);
if?(reader.HasRows?==?false)
{
this.logtext?=?"\r\n"?+?DateTime.Now.ToString()?+?",?內容處理完成。";
textBox1.AppendText(this.logtext);
textBox1.ScrollToCaret();
return;
}
else
{
while?(reader.Read()?==?true)
{
this.curr_id?=?Convert.ToInt32(reader["id"]);
this.curr_title?=?reader["title"].ToString();
this.curr_fileext?=?reader["fileext"].ToString();
this.curr_filesize?=?Convert.ToDouble(reader["filesize"])?*?1024;
}
//do?something?more
}
reader.Close();
this.dbhelper.CloseDBconn();
使用方法(更新數據):this.dbhelper.OpenDBconn();
string?sqlchan?=?"u.p.d.a.t.e?blog?set?isfixed=1?w.h.e.r.e?id=123";
this.dbhelper.execute(sqlchan);
this.dbhelper.CloseDBconn();
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的c winform mysql类_C#连接MySQL数据库操作类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 毕业与计算机专业,电子与计算机工程专业毕
- 下一篇: c语言switch comiti,国际经