c#连接sqlserver数据库

来源:互联网 发布:新概念背诵200遍 知乎 编辑:程序博客网 时间:2024/06/01 08:55

首先需要导入的一些

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;


0 0
原创粉丝点击