C#实现连接SQL Server2012数据库并执行SQL语句的方法

本文实例讲述了C#实现连接SQL Server2012数据库并执行SQL语句的方法。分享给大家供大家参考,具体如下:

开发工具:Visual Studio 2012
数据库: SQL Server 2012

使用Visual Studio时还是直接和微软自家的SQL Server数据库连接比较方便,就像使用Eclipse时和MySQL连接便捷一样的道理

无论使用什么工具步骤都一样:

1. 首先保证相关工具都已经正确安装了
2. 开启数据库连接服务
3. 在开发工具中通过用户名和口令与数据库进行关联
4. 执行SQL语句
5. 关闭相关连接和服务

连接数据库

using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
string connectionString="server=.;database=Sql;uid=sa; pwd=123456";
conn.ConnectionString = connectionString;
conn.open();

server=.server=localhost是一样的意思,都表示连接本地数据库

database后跟数据库的名称

uidpwd就是你数据库访问时的用户名和口令

到这里就可以查看一下数据库连接的状态,可以直接将当前连接的状态输出查看

Console.Write(conn.State.ToString());

如果执行到这里发现有错误,就需要查看一下数据库安装的版本问题,打开SQL Server配置管理器

C#实现连接SQL Server2012数据库并执行SQL语句的方法

正常应该是MSSQLSERVER,博主这里为了测试所以安装了一个简化版的SQLEXPRESS,如果你和博主的版本一样就不能使用上面的连接数据库的方式了

SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = @"(local)\SQLExpress";
scsb.IntegratedSecurity = true;
scsb.InitialCatalog = sqlName;
SqlConnection conn = new SqlConnection(scsb.ConnectionString);
conn.open();

正确连接数据库后,就可以执行SQL语句了

string sqlStr = "SELECT * FROM table1";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sqlStr;
cmd.CommandType = CommandType.Text;
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
Console.Write("共有" + i.ToString() + "条数据");
string sqlStr = "INSERT INTO table1 VALUES('1','a')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sqlStr;
cmd.CommandType = CommandType.Text;
SqlDataReader dataReader = cmd.ExecuteReader();
if(dataReader.HasRows)
{
 while(dataReader.Read())
 {
  for(int i=0; i<dataReader.FieldCount; i++)
  {
   Console.Write(dataReader[i].ToString()+"\t");
  }
 }
}
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
Console.Write("共有" + i.ToString() + "条数据");

最后别忘了关闭数据库连接

conn.Close();

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#常见数据库操作技巧汇总》、《C#常见控件用法教程》、《C#窗体操作技巧汇总》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结

希望本文所述对大家C#程序设计有所帮助。