刚学用C#,有很多不清楚,请大家不吝赐教。
我用C#来写关于数据库查询的程序,当语句要用到参数时,我是这样写的
...
string cstr = ".....";
SqlConnection cnn = new SqlConnection(cstr);
string sql = "select * from base_resource_tb_user where departmentid = @departid";
SqlCommand cmd = new SqlCommand(sql); cmd.Connection = cnn;
cmd.Parameters.Add(new SqlParameter("@departid", "0")); cnn.Open();
IDataReader reader = cmd.ExecuteReader();
...
现在的问题是,当数据库是MS-SQL Server时,程序能正确地运行,但当我将数据库换成是MySQL,并同时将 SqlConnection换成MySqlConnection,SqlCommand 换成 MySqlCommand时,程序就不能正常工作了,究其原因在于参数的写法,经试验在MySQl中要将参数写成是
string sql = "select * from base_resource_tb_user where departmentid = ?departid";
SqlCommand cmd = new SqlCommand(sql); cmd.Connection = cnn;
cmd.Parameters.Add(new SqlParameter("?departid", "0"));
即将@改为?,这样才能正常运行?但MS-SQL Server却不能使用?作参数符。为什么这么奇怪?我原来用Delphi的话,无论是那一种数据库,还是那一种的数据接口(ADO,BDE,DAC等等)都是统一用:的,为什么C#这么奇怪?
我用C#来写关于数据库查询的程序,当语句要用到参数时,我是这样写的
...
string cstr = ".....";
SqlConnection cnn = new SqlConnection(cstr);
string sql = "select * from base_resource_tb_user where departmentid = @departid";
SqlCommand cmd = new SqlCommand(sql); cmd.Connection = cnn;
cmd.Parameters.Add(new SqlParameter("@departid", "0")); cnn.Open();
IDataReader reader = cmd.ExecuteReader();
...
现在的问题是,当数据库是MS-SQL Server时,程序能正确地运行,但当我将数据库换成是MySQL,并同时将 SqlConnection换成MySqlConnection,SqlCommand 换成 MySqlCommand时,程序就不能正常工作了,究其原因在于参数的写法,经试验在MySQl中要将参数写成是
string sql = "select * from base_resource_tb_user where departmentid = ?departid";
SqlCommand cmd = new SqlCommand(sql); cmd.Connection = cnn;
cmd.Parameters.Add(new SqlParameter("?departid", "0"));
即将@改为?,这样才能正常运行?但MS-SQL Server却不能使用?作参数符。为什么这么奇怪?我原来用Delphi的话,无论是那一种数据库,还是那一种的数据接口(ADO,BDE,DAC等等)都是统一用:的,为什么C#这么奇怪?
==
这样就行,对于MySQL这类的数据库,不认参数的名字,只认参数的顺序所有尤其是更新语句要小心
----
之前我用Delphi写过一个通用的查询器的,现在想来,如果用C#去写的话,要注意这些问题了
再晕~~