C#连接数据库sqlserver2005,并执行sql语句实例:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data.SqlClient;//头文件
- namespace DBdemo1
- {
- class Program
- {
- static void Main(string[] args)
- {
- //连接字符串,连接本地的sqlserver服务器
- string connstring = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mapdemo;Data Source=PC-20130306BGML";
- //sql语句,更新表格中的学生姓名
- string sqlstring = "update students set studentname = 'zhangsan' where studentID = '123456'";
- //建立连接
- SqlConnection conn = new SqlConnection(connstring);
- conn.Open();
- //建立数据命令对象
- SqlCommand cmd = new SqlCommand(sqlstring, conn);
- //执行数据命令,返回受影响的行数
- int rowsreturned = cmd.ExecuteNonQuery();
- Console.WriteLine(rowsreturned);
- //关闭连接
- conn.Close();
- }
- }
- }