用代码连接数据库实现增删改自己总结步骤

原文发布时间为:2008-07-24 —— 来源于本人的百度文章 [由搬家工具导入]

首先当然要写上using System.Data.SqlClient;//这句要写上

1、建立连接字符串如下:

SqlConnection testconn = new SqlConnection("Server=.\\SQLEXPRESS;database=test;uid=sa;pwd=123456");
//SQL服务器为.\\SQLEXPRESS,数据库为test,使用sql认证方式,用户名sa,密码123456

SqlConnection testconn = new SqlConnection("Server=.\\SQLEXPRESS;database=test;Integrated Security = True");

//SQL服务器为.\\SQLEXPRESS,数据库为test,使用windows认证方式

2、写SQL语句字符串

string idsql = "SELECT * FROM stu";
string countsql="SELECT COUNT(*) FROM stu";
string textsql = "SELECT * FROM stu WHERE id=" + DropDownList1.SelectedValue;
string addsql="INSERT INTO stu VALUES('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')";
string deletsql = "DELETE FROM stu WHERE id=" + TextBox1.Text;
string upsql = "UPDATE stu SET name='" + TextBox2.Text + "'," + "class='" + TextBox3.Text + "' WHERE id=" + TextBox1.Text;

3、添加命令

SqlCommand sid = new SqlCommand(idsql,testconn);
SqlCommand count = new SqlCommand(countsql,testconn);
SqlCommand stext = new SqlCommand(textsql, testconn);
SqlCommand addcmd = new SqlCommand(addsql, testconn);
SqlCommand deletcmd = new SqlCommand(deletsql, testconn);
SqlCommand upcmd = new SqlCommand(upsql, testconn);

4、打开连接

testconn.Open();

5、执行命令

count.ExecuteScalar();//一般增删改的命令执行都用这个吧
addcmd.ExecuteScalar();
deletcmd.ExecuteScalar();
upcmd.ExecuteScalar();

查询读取数据比较麻烦如下:

SqlDataReader testdr = sid.ExecuteReader();//执行查询时需要个dr
testdr.Read();//执行读取

testdr["列名"];//读取一个值

TextBox1.Text = textdr["id"].ToString();
TextBox2.Text = textdr["name"].ToString();
TextBox3.Text = textdr["class"].ToString();

while(testdr.Read())//testdr.Read()读出某列所有数据
{
   DropDownList1.Items.Add(testdr["id"].ToString());//testdr["id"]读出id列的数据
}

textdr.Close();//最后关闭读取

6、关闭连接

testconn.Close();

---------------------------------------------------------------------------------------------------

以下为本人做的完整实例代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;//这句要写上

public partial class _Default : System.Web.UI.Page
{
    static int k;
    //SqlConnection testconn = new SqlConnection("Server=.\\SQLEXPRESS;database=test;uid=sa;pwd=123456");
    SqlConnection testconn = new SqlConnection("Server=.\\SQLEXPRESS;database=test;Integrated Security = True");
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
        {
           
            //SqlCommand sid = testconn.CreateCommand();
            //SqlCommand count = testconn.CreateCommand();
            //sid.CommandText = "SELECT * FROM stu";
            //count.CommandText = "SELECT COUNT(*) FROM stu";

            string idsql = "SELECT * FROM stu";
            string countsql="SELECT COUNT(*) FROM stu";
            SqlCommand sid = new SqlCommand(idsql,testconn);
            SqlCommand count = new SqlCommand(countsql,testconn);

            try
            {

                testconn.Open();
                //k = (int)count.ExecuteNonQuery();
                k = (int)count.ExecuteScalar();
                SqlDataReader testdr = sid.ExecuteReader();
                while (testdr.Read())
                {
                    DropDownList1.Items.Add(testdr["id"].ToString());
                }
                testdr.Close();
            }
            catch (Exception ex)
            {
                Response.Write("<scirpt>alert('" + ex.Message.ToString() + "')</script>");
            }
            finally
            {
                testconn.Close();
            }
        }

       
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
       
        string textsql = "SELECT * FROM stu WHERE id=" + DropDownList1.SelectedValue;
        SqlCommand stext = new SqlCommand(textsql, testconn);
        testconn.Open();
        SqlDataReader textdr = stext.ExecuteReader();
        textdr.Read();
        TextBox1.Text = textdr["id"].ToString();
        TextBox2.Text = textdr["name"].ToString();
        TextBox3.Text = textdr["class"].ToString();

        textdr.Close();
        testconn.Close();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      
        string addsql="INSERT INTO stu VALUES('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')";
        SqlCommand addcmd = new SqlCommand(addsql, testconn);
        testconn.Open();
        addcmd.ExecuteScalar();
        testconn.Close();
        Response.Redirect(".//default.aspx");
       
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string deletsql = "DELETE FROM stu WHERE id=" + TextBox1.Text;
        SqlCommand deletcmd = new SqlCommand(deletsql, testconn);
        testconn.Open();
        deletcmd.ExecuteScalar();
        testconn.Close();
        Response.Redirect(".//default.aspx");
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        string upsql = "UPDATE stu SET name='" + TextBox2.Text + "'," + "class='" + TextBox3.Text + "' WHERE id=" + TextBox1.Text;
        SqlCommand upcmd = new SqlCommand(upsql, testconn);
        testconn.Open();
        upcmd.ExecuteScalar();
        testconn.Close();
        Response.Redirect(".//default.aspx");
    }
}

时间: 2024-08-24 03:05:22

用代码连接数据库实现增删改自己总结步骤的相关文章

Mybatis 介绍 入门 及连接数据库进行增删改查(步骤)

原文地址:https://www.cnblogs.com/foreverdebug/p/10597284.html

nodejs连接数据库的增删改查

连接数据库后需要用代码操作的是,传入mysql语句,和参数,然后就是回调了 新增 // 新增 app.post('/process_post', urlencodedParser, function (req, res) { //post处理方法 var response = { "names":req.body.names, //得到页面提交的数据 "passwords":req.body.passwords }; //鏈接數據庫 var mysql = requ

连接数据库进行增删改查(基本)上

1.首先在数据库中建表 2.编写工具类,用来连接数据库以及关流,3306是数据库MySQL的端口号 public static Connection getconn() { Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/newdb_17?useUnicode=true&"; try { co

测开之路五十一:代码实现MongoDB增删改查

初始化时连接.析构时断开连接 from pymongo import MongoClient class Mogo(object): def __init__(self, host='127.0.0.1', port=27017): """ 初始化时连接 """ self.connect = MongoClient(host, port) def __del__(self): """ 析构时断开连接 "&q

ListView 连接数据库的增删改查

private string link = "server=.;database=list;user=sa;pwd=123"; public void chaxun() //创建一个查询函数 { SqlConnection coon = new SqlConnection(link); //连接数据库 coon.Open();//打开数据库 SqlCommand cmd = coon.CreateCommand();//创建命令 cmd.CommandText = "sele

PHp连接数据库实现增删改查

首页 删除 添加 添加处理页面 修改 修改处理页面

php课程---练习连接数据库及增删改

方式一:用php中的内置函数来做 (适用于5.1之前的版本) //1.生成连接 $conn = mysql_connect("localhost","root",""); //2.选择操作的数据库 mysql_select_db("today",$conn); //3.写sql语句 $sql = "select * from Info"; //4.执行mysql语句 $result = mysql_quer

php连接数据库与增删改查

方法一,这种方式容易弹出警告: 1.数据访问: $uid="root";用户名 $pwd="123";密码 $host="localhost";服务器 $database="test";连接哪个数据库 2.生成连接: $conn=mysql_connect($host,$uid,$pwd):host服务器 3.选择要操作的数据库: mysql_select_db($database,$conn); 4.执行mySQL语句: $

jmeter连接数据库之增删改查

配置jdbc: 查询sql配置: 插入sql配置: 修改sql配置: 删除sql配置: 原文地址:https://www.cnblogs.com/qtclm/p/10016489.html