zoukankan      html  css  js  c++  java
  • C# 数据库

    连接:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    // 引入数据库管理控件
    using System.Data;
    using System.Data.SqlClient;
    
    namespace ConsoleApplication3
    {
        class Program
        {
            static void Main(string[] args)
            {
                SqlConnection conn = new SqlConnection();  // 初始化一个SqlConnection()类
                conn.ConnectionString = "server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****";  // 连接字符串,格式(注意间隔要使用分号(";")来做分割):"server=数据库名称(据说可以使用"."来表示本地数据库,没试过);database=数据库;uid=账号;pwd=密码"。注:如果使用的是"."进行登陆的话,可以将uid和pwd换成"integrated security=SSPI"即:"server=.;database=数据库名;integrated security=SSPI";
                conn.Open();  // 打开数据库
                SqlCommand comm = new SqlCommand();  // 初始化SqlCommand()类
                comm.Connection = conn;  // 获取连接指针
                comm.CommandType = CommandType.Text;  // 执行的方式,表示以SQL方式执行,另外还有CommandType.StoredProcedure(存储进程方式)。这个在"https://www.cnblogs.com/namejr/p/10398433.html"再讲。
                comm.CommandText = "select * from student;";  // SQL命令
                SqlDataReader dr = comm.ExecuteReader();  // 生成SqlDataReader
                dr.Close();  // 关闭SqlDataReader对象
                conn.Close();  // 关闭数据库连接
            }
        }
    }
    // 判断其状态是否处于关闭状态
                    if (coon.State != ConnectionState.Closed)
                    {
                        coon.Close();
                        Console.WriteLine("成功关闭!");
                    }

    Connection

    使用web.config存放公共信息,有两种方式:1.appsettings。2.connectionstrings

    1.使用appsettings:

    Web.config:
    <?xml version="1.0" encoding="utf-8"?>
    <!--
      有关如何配置 ASP.NET 应用程序的详细信息,请访问
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    <configuration>
      <appSettings>
        <add key="cn" value="server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****;"/>
      </appSettings>
     ............. </configuration> ///////////////////////////////////////////////////////////////////////////////// WebForm1.aspx: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // } protected void Button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.AppSettings["cn"]; try { conn.Open(); this.Literal1.Text = "连接数据库成功..."; }catch(Exception ex) { this.Literal1.Text = ex.Message; } finally { if (conn.State != ConnectionState.Closed) { conn.Close(); } } } } }

    2.以connectionStrings方式:

    Web.Config:
    <?xml version="1.0" encoding="utf-8"?>
    <!--
      有关如何配置 ASP.NET 应用程序的详细信息,请访问
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    <configuration>
      <connectionStrings>
        <add name="cn" connectionString="server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****;" providerName="System.Data.SqlClient"/>
      </connectionStrings>
    </configuration>
    /////////////////////////////////////////////////////////////////////////////
    WebForm1.apsx:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                //
            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
                try
                {
                    conn.Open();
                    this.Literal1.Text = "连接数据库成功...";
                }catch(Exception ex)
                {
                    this.Literal1.Text = ex.Message;
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                }
            }
        }
    }

    command:

    三个属性:connection、commandType、commandText

    三个方法:ExecuteReader()、ExecuteScalar()、ExecuteNonQuery()

    ASPX:
    <div>
            姓名:<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
            <br />
            年龄:<asp:TextBox ID="TextBoxAge" runat="server"></asp:TextBox>
            <br />
            性别:<asp:TextBox ID="TextBoxSex" runat="server"></asp:TextBox>
            <br />
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><asp:Literal ID="Literal1" runat="server"></asp:Literal>
            <asp:GridView ID="GridView1" runat="server"></asp:GridView>
        </div>
    ////////////////////////////////////////////////////////////////////////////////////////////
    CS:
    protected void Page_Load(object sender, EventArgs e)
            {
                //
            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
                try
                {
                    SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                    comm.CommandType = CommandType.Text;
                    int Sex = (this.TextBoxSex.ToString() == "") ? 1 : 0;
                    conn.Open();  // 打开数据库
                    // comm.CommandText = string.Format("insert into student(name,age,sex) values('{0}',{1},{2})", this.TextBoxName.Text.ToString(), this.TextBoxAge.Text.ToString(), Sex);
                    // int columns = comm.ExecuteNonQuery();  // 返回受影响的行数
                    // this.Literal1.Text = string.Format("连接数据库成功,插入{0}行", columns);
                    //
                    // comm.CommandText = "select count(*) from student";
                    // object columns = comm.ExecuteScalar();  // 只返回一列一行的结果
                    // this.Literal1.Text = string.Format("这个表一共有{0}行",columns);
                    //
                    comm.CommandText = "select name,age,sex from student";
                    SqlDataReader dr = comm.ExecuteReader();  // 获取全部搜索出来的对象
                    // 进行数据绑定
                    this.GridView1.DataSource = dr;
                    this.GridView1.DataBind();
                }catch(Exception ex)
                {
                    this.Literal1.Text = ex.Message;
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                }
            }

    SqlDataAdapter:

    先来简单介绍dataset和datatable

    static void Main(string[] args)
            {
                DataSet ds = new DataSet();  // 定义一个数据集
                DataTable dt = new DataTable();  // 定义一个数据表
                dt.TableName = "jr";  // 添加表名
                DataColumn column0 = new DataColumn();  // 定义其中一列
                column0.DataType = typeof(int);  // 定义该列的类型
                column0.AllowDBNull = false;  // 定义该列为非空
                column0.ColumnName = "ID";  // 定义列的名称
                dt.Columns.Add(column0);  // 将该行添加到数据表
                DataColumn column1 = new DataColumn();
                column1.DataType = typeof(string);
                column1.ColumnName = "NAME";
                dt.Columns.Add(column1);
                // 添加数据方式1
                dt.Rows.Add(1, "namejr");  // 添加一行
                // 添加数据方式2
                var row0 = dt.NewRow();
                row0[0] = 2;  // 按下标/索引添加
                row0["NAME"] = "name";  // 按键添加
                ds.Tables.Add(dt);  // 添加到数据集
                //
                // 读取数据
                object obj = ds.Tables[0].Rows[0]["NAME"];
                Console.WriteLine(obj);
            }

    SqlDataAdapter

    using System.Data;
    using System.Data.SqlClient;
    using System.Web.Configuration;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                //
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                /*
                // 简便写法:
                SqlDataAdapter da = new SqlDataAdapter("select name,age,sex from student", WebConfigurationManager.ConnectionStrings["cn"].ConnectionString);  // 使用SqlDataAdapter不需要使用open/close打开或者关闭数据库
                DataSet ds = new DataSet();  // 数据缓存
                da.Fill(ds, "S");  // 填充。fill可以给取出来的缓存表进行取别名
                this.GridView1.DataSource = ds.Tables["S"];
                this.GridView1.DataBind();
                */
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
                try
                {
                    SqlCommand comm = new SqlCommand();  // 创建command
                    comm.Connection = conn;  // 获取连接配置信息
                    comm.CommandType = CommandType.Text;  // 以SQL语句方式执行
                    comm.CommandText = "select name,age,sex from student";  // SQL语句
                    SqlDataAdapter da = new SqlDataAdapter();  // 同上
                    da.SelectCommand = comm;  // 执行操作。此外还有InsertCommand/DeleteCommand/UpdateCommand
                    DataSet ds = new DataSet();
                    da.Fill(ds, "S");
                    this.GridView1.DataSource = ds.Tables["S"];
                    this.GridView1.DataBind();
                }
                catch(Exception err)
                {
                    this.Label1.Text = err.Message;
                }
            }    

     ExecuteReader():只读,向前,独占连接,效率高

    protected void Button1_Click(object sender, EventArgs e)
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
                try
                {
                    SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                    comm.CommandType = CommandType.Text;
                    /*
                    // 只对一个结果集进行读取
                    comm.CommandText = "select name,age,sex from student";
                    conn.Open();
                    SqlDataReader dr = comm.ExecuteReader();
                    // dr.Read()向下读取一条数据,存在数据返回true,不存在数据返回false
                    while (dr.Read())
                    {
                        // 使用下标做索引(有装箱拆箱操作)
                        //this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}, SEX:{2}
    ", dr[0], dr[1], dr[2]);
                        // 使用表名做索引(有装箱拆箱操作)
                        //this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}, SEX:{2}
    ", dr["name"], dr["age"], dr["sex"]);
                        //
                        // 还有一种r.GetXXX(i),不需要进行装箱拆箱,但是必须对应其属性,例如:dr.GetInt32(1)
                    }*/
                    //
                    // 对两个结果集进行操作
                    comm.CommandText = "select name,age from student;select sex from student";  // 获取到的是两个结果集
                    conn.Open();
                    SqlDataReader dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}
    ", dr["name"], dr["age"]);
                    }
                    dr.NextResult();  // 转到下一个结果集
                    while (dr.Read())
                    {
                        this.TextBox1.Text += string.Format("SEX:{0}
    ", dr["sex"]);
                    }
                }
                catch (Exception err)
                {
                    this.Label1.Text = err.Message;
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                }
            }
  • 相关阅读:
    JDBC连接数据库
    Promise的基本用法
    Cookie、LocalStorage 与 SessionStorage的区别在哪里?
    判断时间大小,数值大小
    控制input文本框只能输入正整数
    利用layer弹框代替alert效果,且可以增加callback函数
    input 只能输入数字且控制位数
    递归函数
    分页插件,直接把返回值赋过去即可
    获取选中checkbox的value值
  • 原文地址:https://www.cnblogs.com/namejr/p/10411920.html
Copyright © 2011-2022 走看看