本文是一个利用C# ADO.NET连接SQL Server数据库的程序实例,该实例比较简单,代码如下:
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Text;
- usingSystem.Data;
- usingSystem.Data.SqlClient;
- namespaceDataAccess
- {
- ///<summary>
- ///操作数据库公共类
- ///</summary>
- classSqlDataAccess:IDisposable
- {
- ///<summary>
- ///数据库连接字符串
- ///</summary>
- privatereadonlystringSqlConnectionString="连接字符串;";
- privateSqlConnectionsqlConnection;
- publicSqlDataAccess()
- {
- sqlConnection=newSqlConnection(SqlConnectionString);
- }
执行SQL语句,并返回受影响的行数,具体代码如下:
- ///<summary>
- ///执行SQL语句,并返回数据库受影响的行数
- ///</summary>
- ///<paramnameparamname="sql">SQL语句</param>
- ///<returns></returns>
- publicintExcuteNonQuery(stringsql)
- {
- SqlCommandcmd=newSqlCommand(sql,sqlConnection);
- if(sqlConnection.State==ConnectionState.Closed)
- {
- sqlConnection.Open();
- }
- intresult=cmd.ExecuteNonQuery();
- sqlConnection.Close();
- returnresult;
- }
- //如果更新的数据有特殊字符的用上面那个ExcuteNonQuery()就不行了,需要用到SqlCommand的一个参数SqlParameter。
- publicintExcuteNonQuery(stringsql,SqlParameter[]parameters)
- {
- SqlCommandcmd=newSqlCommand(sql,sqlConnection);
- cmd.Parameters.AddRange(parameters);
- if(sqlConnection.State==ConnectionState.Closed)
- {
- sqlConnection.Open();
- }
- intcount=cmd.ExecuteNonQuery();
- sqlConnection.Close();
- returncount;
- }
返回首行首列的代码如下:
- ///<summary>
- ///返回首行首列
- ///</summary>
- ///<paramnameparamname="sql"></param>
- ///<returns></returns>
- publicobjectExecuteScalar(stringsql)
- {
- SqlCommandcmd=newSqlCommand(sql,sqlConnection);
- if(sqlConnection.State==ConnectionState.Closed)
- {
- sqlConnection.Open();
- }
- objectresult=cmd.ExecuteScalar();
- sqlConnection.Close();
- returnresult;
- }
获取一个DataSet的代码如下:
- ///<summary>
- ///获取一个DataSet
- ///</summary>
- ///<paramnameparamname="sql"></param>
- ///<returns></returns>
- publicDataSetGetDataSet(stringsql)
- {
- SqlDataAdapteradapter=newSqlDataAdapter(sql,sqlConnection);
- DataSetds=newDataSet();
- adapter.Fill(ds);
- returnds;
- }
- }
- }
示例:用上面的数据库连接类,新增一个商品,包括商品名称和单价,代码如下:
- stringinsertSql=@"INSERTINTOPRODUCTINFO
- VALUES
- (
- @PRODUCTNAME,
- @PRODUCTPRICE,
- );
- SqlParameter[]parameters=newSqlParameter[]
- {
- newSqlParameter("@PRODUCTNAME",商品名称){SqlDbTypeSqlDbType=SqlDbType.NVarChar},
- newSqlParameter("@PRODUCTPRICE",商品单价){SqlDbTypeSqlDbType=SqlDbType.Money}
- }
- DataAccessdataAccess=newDataAccess();
- intresult=dataAccess.ExcuteNonQuery(insertSql,parameters);
- if(result>0)
- {
- MessageBox.Show("新增成功");
- }
- else
- {
- MessageBox.Show("新增失败");
- }
本实例就介绍到这里,如果想了解更多SQL Server数据库的知识,这里的文章很值得一看:http://database.51cto.com/sqlserver/,千万不要错过哦!
【编辑推荐】