c#连接sql2000

在控制台应用程序下连接SQL,数据库使用MSSQL自带的Northwind.

1. 创建sqlconnection类的连接对象
SqlConnection mySqlConnection =
new Sqlconnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
//server指定运行sql的计算机名,localhost是常用名表示程序所在的计算机

2.建立sqlcommand对象
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

3.设置SqlCommand对象的CommandText属性
mySqlCommand.CommandText =
"SELECT CustomerID,CompanyName,ContactName,Address" +
"FROM Customer" +
"WHERE CustomerID = 'ALFKI' ";

4.打开sqlconnection对象
mySqlConnection.Open();

5.运行SELECT语句
SqlDataReader mySqlDataReader = mySqlCommad.ExecuteReader();
//调用ExecuteReader()方法运行SELECT,返回一个SqlDataReader对象

6.读行
mySqlDataReader.Read();

7.显示SqlDataReader对象中的列值
Console.WriteLine("mySqlDataReader[/"CustomerId/"]="+
mySqlDataReader["CustomerID"]");
//以下依次是Commpanyname等项...

8.关闭Sqlconnection的连接
mySqlConnection.Close();  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
使用C#连接SQL Server数据库可以使用 ADO.NET 技术,以下是一个简单的例子: 首先需要在代码中添加对 System.Data.SqlClient 的引用。 然后,在代码中创建 SqlConnection 对象,并指定连接字符串: ```csharp using System.Data.SqlClient; string connectionString = "Data Source=服务器名;Initial Catalog=数据库名;User ID=用户名;Password=密码"; SqlConnection connection = new SqlConnection(connectionString); ``` 其中,Data Source 是服务器名称,Initial Catalog 是数据库名称,User ID 和 Password 是连接数据库所需的用户名和密码。 接着,打开连接: ```csharp connection.Open(); ``` 可以使用 SqlCommand 对象来执行 SQL 命令: ```csharp string sql = "SELECT * FROM 表名"; SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(); ``` 使用 ExecuteReader 方法执行查询操作,返回一个 SqlDataReader 对象,可以使用该对象读取查询结果。 最后,关闭连接: ```csharp reader.Close(); connection.Close(); ``` 完整的代码示例: ```csharp using System; using System.Data.SqlClient; class Program { static void Main(string[] args) { string connectionString = "Data Source=服务器名;Initial Catalog=数据库名;User ID=用户名;Password=密码"; SqlConnection connection = new SqlConnection(connectionString); try { connection.Open(); string sql = "SELECT * FROM 表名"; SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("{0}\t{1}\t{2}", reader[0], reader[1], reader[2]); } reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { connection.Close(); } Console.ReadKey(); } } ``` 注意事项: - 连接字符串中的用户名和密码应该是有权限访问数据库的用户。 - 执行 SQL 命令时,应该使用参数化查询来避免 SQL 注入攻击。 - 在使用完 SqlDataReader 对象后,应该关闭连接以释放资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值