/ 中存储网

在c#程序中连接操作MySQL数据库的代码演示

2014-07-13 16:27:51 来源:中存储网
下面是创建一个数据库链接
using MySQLDriverCS;
MySQLConnection conn = new MySQLConnection( new MySQLConnectionString("localhost","test","root","").AsString );
conn.Open();
如果你使用的是.net的集成开发环境(visual studio.net)那么在代码中输入MySQLDriverCS后再输入一个”.”就可以看到MySQLDriverCS名称空间中的所有的东西了.

下面是commond

MySQLCommand cmd;
cmd = new MySQLDriverCS.MySQLCommand("DROP TABLE IF EXISTS test.mysqldrivercs_test",conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd = new MySQLDriverCS.MySQLCommand("CREATE TABLE test.mysqldrivercs_test("+
"SettingID tinyint(3) unsigned NOT NULL auto_increment,"+
"SettingValue text, "+
"PRIMARY KEY (SettingID), UNIQUE KEY SettingID(SettingID), KEY SettingID_2 (SettingID))"+
" TYPE=MyISAM DEFAULT CHARSET=gbk COMMENT='MySQL test table'",conn);
cmd.ExecuteNonQuery();
cmd.Dispose();

下面是insert:

string Value = "Value";
int SettingID = 1;
new MySQLInsertCommand(conn,
new object[,] {{"SettingID",SettingID},{"SettingValue",Value}},
"mysqldrivercs_test"
);

下面是update

Value = "Value2";
new MySQLUpdateCommand(conn,
new object[,] {{"SettingValue",Value}},
"mysqldrivercs_test",
new object[,] {{"SettingID","=",SettingID}},
null
);

下面是select
DataTable dt = new MySQLSelectCommand(conn,
new string[] {"SettingID","SettingValue"},
new string[] {"mysqldrivercs_test"},
new object[,] {{"SettingID","=",SettingID}},
null,
null
).Table;
string storedValue = dt.Rows[0]["SettingValue"].ToString();

下面是delete
new MySQLDeleteCommand(conn,"mysqldrivercs_test",new object[,] {{"SettingID","=",SettingID}},null);

关闭链接

conn.Close();
怎么样,很方便吧!