c#2005中winform如何连接数据库

 建立一个Conn.cs类文件

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


namespace Example
{
  
    // <summary>
    /// Connect 的摘要说明
    /// </summary>
    /// <summary>
    /// 数据库操作类
    /// </summary>
    public class Conn
    {
        public static SqlConnection conn = new SqlConnection("data source=127.0.0.1;initial catalog=WebRollCall;persist security info=False;user id=sa;password=sa;workstation id=127.0.0.1;packet size=4096");  //静态构造一个数据库打开的连接,ConfigurationSettings.AppSettings[0]为web.config配置文件中声明的数据库连接字符串


        public static DataTable BindTable(string sqlstr) //静态方法;参数sqlstr为数据库查询语句,将从数据库中获得的数据填充到一个DataTable中,返回该DataTable
        {
            SqlDataAdapter cmd = new SqlDataAdapter(sqlstr, conn);
            DataTable dt = new DataTable();
            cmd.Fill(dt);
            return dt;
        }

        public static DataTable BindTable(string sqlstr, string condition) //静态方法;参数sqlstr为数据库查询语句,参数condition为查询条件,将从数据库中获得的数据填充到一个DataTable中,返回该DataTable
        {
            SqlDataAdapter cmd = new SqlDataAdapter(sqlstr + condition, conn);
            DataTable dt = new DataTable();
            cmd.Fill(dt);
            return dt;
        }

        public static SqlDataReader BindReader(string sqlstr) //静态方法;参数sqlstr为数据库查询语句,将SqlDataReader指向从数据库中获得的数据,返回该SqlDataReader
        {
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            SqlDataReader dr = cmd.ExecuteReader();
            return dr;
        }

        public static SqlDataReader BindReader(string sqlstr, string condition) //静态方法;参数sqlstr为数据库查询语句,参数condition为查询条件,将SqlDataReader指向从数据库中获得的数据,返回该SqlDataReader
        {
            SqlCommand cmd = new SqlCommand(sqlstr + condition, conn);
            SqlDataReader dr = cmd.ExecuteReader();
            return dr;
        }

        public static void ExecuteSql(string sql)
        {
            try
            {
                conn.Open();
                SqlCommand myCmd = new SqlCommand(sql, conn);
                myCmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception exc)
            {
                string s = exc.ToString();
                conn.Close();
            }
        }
    }
}

 

 

 

 

然后建立窗体Form1.cs

主要相关引用为

using System.Data.SqlClient;
using System.Configuration;

 

 

  #region 取信息
        /// <summary>
        /// 取信息
        /// </summary>
        private void OpenIp()
        {
            //初始化
            string sql = " SELECT   *  FROM  a  ";
            DataTable dt = Conn.BindTable(sql);
            if (dt.Rows.Count != 0)
            {
                if (dt.Rows[0]["a"].ToString().Replace("'", "''").Trim() != "")
                {
                    string ax = dt.Rows[0]["a"].ToString().Replace("'", "''").Trim();                
                }
            }
        }

你可能感兴趣的:(数据库,exception,String,C#,cmd,WinForm)