您的位置:首页 > 数据库

c#连接sqlserver数据库

2014-08-07 16:20 260 查看
首先需要导入的一些

using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;

namespace WebApplication5
{
public class DBHelper
{
private static string dbIP = "127.0.0.1";
private static string dbName = "myTest";
private static string dbUserName = "yang";
private static string dbUserPwd = "yang";

private SqlConnection conn;

//获取数据库连接
public SqlConnection getConn() {
string strconn = @"server="+dbIP+";database="+dbName+";uid="+dbUserName+";pwd="+dbUserPwd+"";
conn = new SqlConnection(strconn);

try
{
conn.Open();
}
catch (System.Exception ex)
{

Console.WriteLine("[ERROR] 数据库操作出现异常:" + ex.Message);
}

return conn;
}

//查询操作
public SqlDataReader search(string str)
{
conn = getConn();
SqlCommand myCommand = new SqlCommand(str,conn);

SqlDataReader rd = myCommand.ExecuteReader();

return rd;
}

//增删改数据
public int addOrDelOrUpdata(string str) {
int result = 0;
conn = getConn();
string strConn = @"" + str;

SqlCommand myCommand = new SqlCommand(strConn, conn);

try
{
result = myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.",ex);
}
return result;
}

//关闭sqldatareader连接
public void closeSqlDataReader(SqlDataReader rd) {
if (rd != null) {
rd.Close();
}
}

//关闭sqlconnection连接
public void closeConn(SqlConnection conn) {
if (conn != null) {
conn.Close();
}
}

}
}

实际使用中直接调用改DBHelper的方法,传入需要的sql语句

select * from tbTree

update tbTree set Context = 'xxxx' where id = 1;

insert into tbTree values('苏州',19);

delete from tbTree where id = 16;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#