c#怎么书写连接sqlserver数据库的语句

2024-12-02 18:37:47
推荐回答(1个)
回答1:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Net;

namespace HR_Checker.common
{
    class sqldate_111
    {
        private string conn = "server=127.0.0.1;database=main;uid=sa;pwd=@12345;Max Pool Size = 1000;Connection Timeout=180";

        public SqlConnection ExceCon()
        {
            SqlConnection connection = new SqlConnection(this.conn);
            connection.Open();
            return connection;
        }

        public SqlDataReader ExceDr(string cmdtxt)
        {
            SqlCommand command = new SqlCommand(cmdtxt, this.ExceCon());
            return command.ExecuteReader();
        }

        public DataSet ExceDS(string cmdtxt, string tblName)
        {
            SqlConnection connection = this.ExceCon();
            DataSet dataSet = null;
            try
            {
                SqlCommand command = new SqlCommand(cmdtxt, connection);
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = command;
                dataSet = new DataSet(tblName);
                adapter.Fill(dataSet);
            }
            catch
            {
                connection.Close();
            }
            return dataSet;
        }

        public bool ExceSQL(string cmdtxt)
        {
            bool flag;
            SqlCommand command = new SqlCommand(cmdtxt, this.ExceCon());
            try
            {
                command.ExecuteNonQuery();
                flag = true;
            }
            catch
            {
                flag = false;
            }
            finally
            {
                this.ExceCon().Close();
            }
            return flag;
        }
    }
}

你在外边引用这个类  sqldate_111 data = new common.sqldate_111()

下面

DataSet ds = data.ExceDS(sql, "dd");

DataTable dt = ds.Tables[0];

dt 是返回表

this.data111.ExceSQL(insertsql); 这个是执行sql语句

记得修改命名空间