老師讓寫一個圖書管理,編輯公共變數后,寫到第三個表單除錯的時候開始出現這個問題,然后進度就卡在這個圖書更新位置,應該怎么改?
class DataAccess
{
private static string ConnectString = "Data Source=localhost;InitialCatalog=Book;Integrated Security=true";
/// <summary>
/// 根據表名獲取資料集的表
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static DataTable GetDataSetByTableName(string table)
{
using (SqlConnection con = new SqlConnection(ConnectString))
{
string sql = "select*from" + table + "";
try
{
SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
adapter.Fill(ds, "table");
return ds.Tables[0];
}
catch (SqlException ex)
{
//例外處理
throw new Exception(ex.Message);
}
}
}
/// <summary>
/// 根據SQL陳述句獲取資料物件
/// </summary>
/// <param name="sql"</param>
/// <returns></returns>
public static DataTable GetDataSetBySql(string sql)
{
using (SqlConnection con = new SqlConnection(ConnectString))
//創建資料庫連接物件
{
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);//創建配接器物件
DataSet ds = new DataSet();//創建資料收集物件
try
{
adapter.Fill(ds);//填充資料集
return ds.Tables[0];//回傳資料集
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
}
}
///<summary>
///根據id值獲取DataReader物件
///</summary>
///<param name="id"</param>
/// <returns></returns>
public static SqlDataReader GetDataReaderByID(int id)
{
using (SqlConnection con = new SqlConnection(ConnectString))
{
string sql = "slecet*from bookinfo where bookid=" + id;//Sql陳述句
try
{
SqlCommand comm = new SqlCommand(sql, con);//創建Command物件
con.Open();//打開鏈接
SqlDataReader reader = comm.ExecuteReader();//創建DataReader物件
reader.Read();//讀取資料
return reader;//回傳DataReader
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
}
}
///<summary>
///更新資料
///</summary>
///<param name="sql"></param>
///<returns></returns>
public static bool UpdataDataTable(string sql)
{
using (SqlConnection con = new SqlConnection(ConnectString))
{
try
{
con.Open();//打開鏈接
SqlCommand comm = new SqlCommand(sql, con);//創建Commons物件
if (comm.ExecuteNonQuery() > 0)//執行更新
{
return true;
}
else
{
return false;
}
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
}
}
///<summary>
///根據資料集和SQL陳述句更新資料庫
///</summary>
///<param name="ds"</param>
///<param name="sql"</param>
public static void UpdateDataSet(DataSet ds, string sql)
{
using (SqlConnection con = new SqlConnection(ConnectString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(sql, con);//創建配接器
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);//根據配接器自動生成表單
adapter.Update(ds, "table");
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
}
}
}
uj5u.com熱心網友回復:
是不是這里少了一個空格?"...; Initial Catalog=Book; ..."
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/113454.html
標籤:ASP.NET
下一篇:求解:ServerVersion = “connection.ServerVersion”引發了“System.InvalidOperationExceptio
