sql資料庫簡單增刪改查

2021-08-14 09:39:06 字數 2681 閱讀 3728

1對於sqlserver這一塊

1、新增引用

using system.data;

using system.data.sqldata;

2、建立於資料庫的連線,建議將它做成乙個方法,方便多次利用。

string sqlconnection = "data source = "註解1";database = 註解2;uid = "註解3";pwd ="註解4"";(其實還有很多種寫法)

3、經常用到的物件有:sqlconnection,sqladapter,sqlcommand、dataset、datagrid和 datareader等,以sqlconnection,sqladapter,sqlcommand、dataset、datagrid物件,操作 sql的例項資料庫northwind中的categorys表為例說明(假定資料庫在本地,資料庫訪問的使用者名為user,密碼為123456):

接下來做一下四個操作的實現

第一、查詢資料:

string myconn="server=127.0.0.1;uid=user;pwd=123456;database=northwind;trusted_connection=no";//定義資料庫連線引數

sqlconnection myconnection=new sqlconnection(myconn);//定義乙個資料連線例項

sqlcommand mycommand=new sqlcommand("select categoryid, categoryname, description from categories",myconnection); //定義乙個資料庫操作指令

sqldataadapter selectadapter=new sqldataadapter();//定義乙個資料介面卡

selectadapter.selectcommand=mycommand;//定義資料介面卡的操作指令

dataset mydataset=new dataset();//定義乙個資料集

myconnection.open();//開啟資料庫連線

selectadapter.selectcommand.executenonquery();//執行資料庫查詢指令

myconnection.close();//關閉資料庫

selectadapter.fill(mydataset);//填充資料集

datagrid1.datasource=mydataset;

datagrid1.databind();//將資料**用資料集中的資料填充

第二、新增資料

string myconn="server=127.0.0.1;uid=user;pwd=123456;database=northwind;trusted_connection=no";

sqlconnection myconnection=new sqlconnection(myconn);

string myinsert="insert into categories(categoryname, description)values('"+convert.tostring(textbox2.text)+"','"+convert.tostring(textbox3.text)+"')";

sqlcommand mycommand=new sqlcommand(myinsert,myconnection);

try//異常處理

catch(exception ex)

exception caught.", ex);}第

三、修改資料

string categoryname=textbox2.text;

string categorydescription=textbox3.text;

string myconn="server=127.0.0.1;uid=user;pwd=123456;database=northwind;trusted_connection=no";

sqlconnection myconnection=new sqlconnection(myconn);

string myupdate="update categories set categoryname='"+categoryname+"',description='"+categorydescription+"' where categoryid="+textbox1.text;

sqlcommand mycommand=new sqlcommand(myupdate,myconnection);

trycatch(exception ex)

exception caught.", ex);}第

四、刪除資料

string myconn="server=127.0.0.1;uid=user;pwd=123456;database=northwind;trusted_connection=no";

sqlconnection myconnection=new sqlconnection(myconn);

string mydelete="delete from categories where categoryid="+textbox1.text;

sqlcommand mycommand=new sqlcommand(mydelete,myconnection);

trycatch(exception ex)

exception caught.", ex);

}

簡單的資料庫增刪改查

sqlserver語句的增刪改查 語法 insert into 表名 列名1,列名2,列名3,列名4 values 資料1,資料2,資料3,資料4 insert into stuinfo sid,sname,saddress,sclass,s values 1,碼仙1 火星 1001,男 這是插入語...

資料庫增刪改查

我們知道當我們的表建立後重複執行會出錯,一般我們會這麼處理 create table if not exists stuinfo 學了新建表我們還應該知道乙個東西,如何刪除表 deop table table name 怎麼檢視別人的見表語句呢 show create table stuinfo 怎...

資料庫增刪改查

import pymysql def getmysqlconn conn pymysql.connect host 172.16.238.130 port 3306,db my mysql user root password 123456 charset utf8 return conn def ...