大家好,我用C#写连接SQLSERVER的代码,虽然能成功运行,但感觉不怎么完整,比如是否要手动关闭连接,是否要写异常处理等等。麻烦大家帮我看看代码,给我完整的建议可以吗?
实现功能是将数据库的内容显示在GridView控件中,程序能运行成功,就是担心代码不完整。代码如下:SqlConnection conn = new SqlConnection("server=localhost;database=BOE;user=sa;password=640407");//这里是否要用open()方法呢,为什么我不用也可以运行呢?SqlCommand cmd = new SqlCommand("select SupplierName,Contact,Mobile from Supplier", conn);SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;da.Fill(ds, "dbo.Supplier");this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
//是否要手动关闭连接呢?//异常处理如何写呢?
实现功能是将数据库的内容显示在GridView控件中,程序能运行成功,就是担心代码不完整。代码如下:SqlConnection conn = new SqlConnection("server=localhost;database=BOE;user=sa;password=640407");//这里是否要用open()方法呢,为什么我不用也可以运行呢?SqlCommand cmd = new SqlCommand("select SupplierName,Contact,Mobile from Supplier", conn);SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;da.Fill(ds, "dbo.Supplier");this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
//是否要手动关闭连接呢?//异常处理如何写呢?
解决方案 »
- C#用Datatable读取oracle数据问题
- 求:基于MVVM设计模式的WPF浏览器应用程序Dome
- 如何把一组由dll得到byte[]保存为DLL。。
- 关与两个像素点的相似度,或者根据颜色模糊查询相似颜色!
- C#.net用什么报表控件比较好呀(免费的,自带的不免费,郁闷中)
- 请教数据库中“存储过程”
- 如何在标题栏增加一个置顶按钮
- 就这50分了,帮我解决了我好去做事
- 如何防止我手写的代码被可视化编辑器自动更改?
- 请教一个问题:在制作WINDOWS APP安装程序的时候,我要在用户选定安装路径后修改用户注册表,应该怎么操作?
- WinAPI的mouse_event如何模拟鼠标点击?有问题源码 谢谢
- Session获取登录用户数量及具体值
异常处理可以用try catch
如果是大型项目的话,链接不关闭会占用内存,等待垃圾回收,会影响性能
{
OracleConnection conn = new OracleConnection(ConnectionString);
OracleCommand cmd = new OracleCommand(sql,conn);
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
try
{
conn.Open();
OracleDataAdapter ad = new OracleDataAdapter();
ad.SelectCommand = cmd;
ad.Fill(ds);
}
catch (Exception ex)
{
strError = "数据查询失败:" + ex.Message;
return null;
}
finally
{
conn.Close();
}
return ds;
}
这是一个例子,包括异常判断
using (SqlConnection conn = new SqlConnection(SqlStr))
{
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "select * from...";
command.CommandType = System.Data.CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataSet ds = new DataSet();
sda.Fill(ds);
}或者可以用SqlConnectionStringBuilder
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "数据源";
scsb.InitialCatalog = "初始目录";
scsb.IntegratedSecurity = true;
scsb.UserID = "";
scsb.Password = "";
string SqlStr = scsb.ConnectionString;
using (SqlConnection conn = new SqlConnection(SqlStr))
{
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "select * from...";
command.CommandType = System.Data.CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataSet ds = new DataSet();
sda.Fill(ds);
}
异常处理可以用try catch
访问数据库的一帮都要加上异常处理防止程序崩溃。新手建议,高手勿喷。