C#连接sql server2005数据库

小咪咪 2022-09-17 11:27 338阅读 0赞

网上关于C#连接sal server2005的资料不多,也不全面,对于一个初学者来说要花很长时间看懂。本人经过查找资料和自己的总结,来分享下成果:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Data.SqlClient;
  8. namespace WebTest2.webRoot
  9. {
  10. public partial class JDBC : System.Web.UI.Page
  11. {
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. //建立数据库连接字符串
  15. string connectionString = "server=localhost;database=test;uid=sa;pwd=123";
  16. //将连接字符串传入SqlConnection对象的构造函数中
  17. SqlConnection mySqlConnection = new SqlConnection(connectionString);
  18. try
  19. {
  20. //打开连接
  21. mySqlConnection.Open();
  22. //利用label控件显示mySqlConnection对象的ConnectionString属性
  23. lblInfo.Text = "mySqlConnection对象的ConnectionString属性为:" +
  24. mySqlConnection.ConnectionString;
  25. lblInfo1.Text += "mySqlConnection对象的ConnectionTimeout属性为" +
  26. mySqlConnection.ConnectionTimeout;
  27. lblInfo2.Text += "mySqlConnection对象的Database属性为" +
  28. mySqlConnection.Database;
  29. lblInfo3.Text += "mySqlConnection对象的DataSource属性为" +
  30. mySqlConnection.DataSource;
  31. lblInfo4.Text += "mySqlConnection对象的PacketSize属性为" +
  32. mySqlConnection.PacketSize;
  33. lblInfo5.Text += "mySqlConnection对象的ServerVersion属性为" +
  34. mySqlConnection.ServerVersion;
  35. lblInfo6.Text += "mySqlConnection对象的当前状态为" +
  36. mySqlConnection.State;
  37. }
  38. catch (Exception err)
  39. {
  40. lblInfo7.Text = "读取数据库出错";
  41. lblInfo8.Text += err.Message;
  42. }
  43. finally
  44. {
  45. //关闭与数据库的连接
  46. mySqlConnection.Close();
  47. lblInfo9.Text += "关闭连接后的mySqlConnection对象的状态为";
  48. lblInfo10.Text += mySqlConnection.State.ToString();
  49. }
  50. }
  51. }
  52. }

注意:如果你的开发工具中没有提示SqlConnection,你需要引入using System.Data.SqlClient;下面教你如何创建出代码中的类:

![Image 1][]

会生出成三个文件

![Image 1][]

上面代码在JDBC.aspx.cs中写。

lblInfo.Text 调用的是JDBC.aspx的textBox中的id属性, 可以在视图的工具箱拖控件!

![Image 1][]

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,338人围观)

还没有评论,来说两句吧...

相关阅读