1. 连接本地数据库的语句 string str_conn = "server=.;database=Employees;Trusted_Connection=SSPI;";
2. 使用DataSet获取数据库返回的数据
string str_conn = "server=.;database=Employees;Trusted_Connection=SSPI;"; string sql = string.Format( "select * from Admin where LoginID='{0}' and Password='{1}'", this.textBoxUser.Text = loginId, this.textBoxPas.Text = loginPwd); SqlConnection sqlconn = new SqlConnection(str_conn); sqlconn.Open(); SqlDataAdapter sda = new SqlDataAdapter(sql,str_conn); DataSet ds1 = new DataSet(); sda.Fill(ds1); int count = ds1.Tables[0].Rows.Count;
创建存储过程:
SET @变量名=值
SELECT @变量名= 值
IF (条件)
BEGIN
语句1
语句2
……
END
ELSE
BEGIN
语句1;
语句2;
……
ENDWHILE (条件)
BEGIN
语句1
语句2
……
BREAK
END
CREATE TRIGGER trigger_name
ON table_name
[WITH ENCRYPTION]
FOR [DELETE,INSERT, UPDATE]
AS
T-SQL语句
GO
实例:CREATE TRIGGER trig_transInfo
ON transInfo
FOR INSERT
AS
DECLARE @type char(4),@outMoney MONEY
DECLARE @myCardIDchar(10),@balance MONEY
SELECT @type=transType,@outMoney=transMoney,
@myCardID=cardIDFROM inserted
IF (@type='支取')
UPDATE bank SET currentMoney=currentMoney-@outMoney
WHERE cardID=@myCardID
ELSE
UPDATE bank SET currentMoney=currentMoney+@outMoney
WHERE cardID=@myCardID
…..
GO
事务:
BEGIN TRANSACTION
/*--定义变量,用于累计事务执行过程中的错误--*/
DECLARE @errorSum INT
SET @errorSum=0 --初始化为0,即无错误
/*--转帐:张三的帐户少1000元,李四的帐户多1000元*/
UPDATE bank SET currentMoney=currentMoney-1000
WHERE customerName='张三'
SET @errorSum=@errorSum+@@error
UPDATE bank SET currentMoney=currentMoney+1000
WHERE customerName='李四'
SET @errorSum=@errorSum+@@error --累计是否有错误
IF @errorSum<>0 --如果有错误
BEGIN
print '交易失败,回滚事务'
ROLLBACK TRANSACTION
END
ELSE
BEGIN
print '交易成功,提交事务,写入硬盘,永久的保存'
COMMITTRANSACTION
END
GO
print '查看转帐事务后的余额'
SELECT * FROMbank
GO
游标:
DataReader类:
•需要永久连接
•只读和只进访问
• Read方法使Reader前进到下一个记录,当有多个结果集时用分号分割各select语句,并使用NextResult方法访问下一个结果集,这样可节省与数据库的链接次数。
•执行给定查询、从数据流中检索行,并将结果集绑定到 DataReader类的给定实例
•
•访问记录中的字段有两种方法:
•
1、Item属性(直接获取索引指定的条目)
2、GetXXX方法(该方法根据后缀自动转换类型)如myReader.GetString(1);