用于SqlServer数据库的SqlServerHelper.cs类,及其调用例子
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.Data;using System.Data.SqlClient;namespace demo{ public abstract class SqlServerHelper { public static string ConnStr
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace demo { public abstract class SqlServerHelper { public static string ConnString = string.Empty; public static string Conn_Config_Str_Name = string.Empty; public static string Conn_Server = string.Empty; public static string Conn_DBName = string.Empty; public static string Conn_Uid = string.Empty; public static string Conn_Pwd = string.Empty; private static string _ConnString { get { if (!string.IsNullOrEmpty(ConnString)) return ConnString; object oConn = ConfigurationManager.ConnectionStrings[Conn_Config_Str_Name]; if (oConn != null && oConn.ToString() != "") return oConn.ToString(); return string.Format(@"server={0};database={1};uid={2};password={3}", Conn_Server, Conn_DBName, Conn_Uid, Conn_Pwd); } } // 测试连接 public static bool TestConn() { SqlConnection myConn = null; bool bResult = false; try { myConn = new SqlConnection(_ConnString); myConn.Open(); } catch (Exception ex) { } finally { if (myConn != null && myConn.State.ToString() == "Open") bResult = true; } myConn.Close(); return bResult; } // 取datatable public static DataTable GetDataTable(out string sError, string sSQL) { DataTable dt = null; sError = string.Empty; try { SqlConnection conn = new SqlConnection(_ConnString); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = sSQL; SqlDataAdapter dapter = new SqlDataAdapter(comm); dt = new DataTable(); dapter.Fill(dt); } catch (Exception ex) { sError = ex.Message; } return dt; } // 取dataset public static DataSet GetDataSet(out string sError, string sSQL) { DataSet ds = null; sError = string.Empty; try { SqlConnection conn = new SqlConnection(_ConnString); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = sSQL; SqlDataAdapter dapter = new SqlDataAdapter(comm); ds = new DataSet(); dapter.Fill(ds); } catch (Exception ex) { sError = ex.Message; } return ds; } // 取某个单一的元素 public static object GetSingle(out string sError, string sSQL) { DataTable dt = GetDataTable(out sError, sSQL); if (dt != null && dt.Rows.Count > 0) { return dt.Rows[0][0]; } return null; } // 取最大的ID public static Int32 GetMaxID(out string sError, string sKeyField, string sTableName) { DataTable dt = GetDataTable(out sError, "select isnull(max([" + sKeyField + "]),0) as MaxID from [" + sTableName + "]"); if (dt != null && dt.Rows.Count > 0) { return Convert.ToInt32(dt.Rows[0][0].ToString()); } return 0; } // 执行 insert,update,delete 动作,也可以使用事务 public static bool UpdateData(out string sError, string sSQL, bool bUseTransaction = false) { int iResult = 0; sError = string.Empty; if (!bUseTransaction) { try { SqlConnection conn = new SqlConnection(_ConnString); if (conn.State != ConnectionState.Open) conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = sSQL; iResult = comm.ExecuteNonQuery(); } catch (Exception ex) { sError = ex.Message; iResult = -1; } } else // 使用事务 { SqlTransaction trans = null; try { SqlConnection conn = new SqlConnection(_ConnString); if (conn.State != ConnectionState.Open) conn.Open(); trans = conn.BeginTransaction(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = sSQL; cmd.Transaction = trans; iResult = cmd.ExecuteNonQuery(); trans.Commit(); } catch (Exception ex) { sError = ex.Message; iResult = -1; trans.Rollback(); } } return iResult > 0; } } }
调用方法:
一,先设置数据库连接的信息
//SqlServerHelper.ConnString = @"server=电脑名 或 电脑IP;database=数据库名;uid=数据库登录名;password=数据库登录密码";
SqlServerHelper.Conn_Config_Str_Name = @"ConnString"; // ConnString的信息在 App.Config里设置 //SqlServerHelper.Conn_Server = @"电脑名 或 电脑IP"; //SqlServerHelper.Conn_DBName = "数据库名"; //SqlServerHelper.Conn_Uid = "数据库登录名"; //SqlServerHelper.Conn_Pwd = "数据库登录密码";
二, App.Config
三, 读取 datatable / dataset 数据
private void InitGrid() {
string sSQL = "select * from test";
string sError = string.Empty;
DataTable dt = SqlServerHelper.GetDataTable(out sError, sSQL);
//DataSet dt = SqlServerHelper.GetDataSet(out sError, sSQL);
dataGridView1.DataSource = dt;
if (!string.IsNullOrEmpty(sError)) Common.DisplayMsg(this.Text, sError);
}
四,插入,修改,删除 数据 (都调用SqlServerHelper.UpdateData方法)
// 插入
string sError = string.Empty; int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test") + 1; string sSql = "insert into test select " + iMaxID + ",'name" + iMaxID + "','remark" + iMaxID + "'"; sError = string.Empty; bool bResult = SqlServerHelper.UpdateData(out sError, sSql, true); if (bResult) Common.DisplayMsg(this.Text, "插入成功"); else Common.DisplayMsg(this.Text, sError);
InitGrid();
// 修改
sError = string.Empty; int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test"); string sSql = "update test set name='name_jonse',remark='remark_jonse' where id=" + iMaxID; sError = string.Empty; bool bResult = SqlServerHelper.UpdateData(out sError, sSql, true); if (bResult) Common.DisplayMsg(this.Text, "修改成功"); else Common.DisplayMsg(this.Text, sError);
InitGrid();
// 删除
sError = string.Empty; int iMaxID = SqlServerHelper.GetMaxID(out sError, "id", "test"); string sSql = "delete from test where id=" + iMaxID; sError = string.Empty; bool bResult = SqlServerHelper.UpdateData(out sError, sSql); if (bResult) Common.DisplayMsg(this.Text, "删除成功"); else Common.DisplayMsg(this.Text, sError);
InitGrid();
五,其它
public static void DisplayMsg(string sCaption, string sMsg) { sMsg = sMsg.TrimEnd('!').TrimEnd('!') + " !"; MessageBox.Show(sMsg, sCaption); }

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック

インポート手順は次のとおりです。 MDF ファイルを SQL Server のデータ ディレクトリ (通常は C:\Program Files\Microsoft SQL Server\MSSQL\DATA) にコピーします。 SQL Server Management Studio (SSMS) でデータベースを開き、[アタッチ] を選択します。 「追加」ボタンをクリックして、MDF ファイルを選択します。データベース名を確認し、「OK」ボタンをクリックします。

SQL Server データベースを誤って削除した場合は、次の手順を実行して回復できます: データベース アクティビティの停止、ログ ファイルのバックアップ、データベース ログの確認、回復オプション: バックアップからの復元、トランザクション ログからの復元、DBCC CHECKDB の使用、3 番目の使用パーティーツール。データ損失を防ぐために、データベースを定期的にバックアップし、トランザクション ログを有効にしてください。

SQL Server のインストールが失敗した場合は、次の手順に従ってクリーンアップできます。 SQL Server をアンインストールする レジストリ キーを削除する ファイルとフォルダーを削除する コンピューターを再起動する

MySQL と SQL Server の構文の違いは、主にデータベース オブジェクト、データ型、SQL ステートメント、その他の側面に反映されています。データベース オブジェクトの違いには、ストレージ エンジン、ファイル グループの指定方法、インデックスと制約の作成などが含まれます。データ型の違いには、数値型、文字型、日付と時刻の型の違いが含まれます。 SQL ステートメントの違いは、結果セットの制限、データの挿入、更新および削除の操作などに反映されます。その他の違いには、ID 列、ビュー、ストアド プロシージャの作成方法が含まれます。異なるデータベース システムを使用する際のエラーを回避するには、これらの違いを理解することが重要です。

SQL Server データベースを削除するには、次の手順を順番に実行してください: 1. SQL Server Management Studio にログインします; 2. データベース ノードを展開します; 3. 削除するデータベースを右クリックします; 4. [削除] を選択します。 5. 削除を確認します。注: データベースを削除すると元に戻すことはできません。重要なデータをバックアップし、他のオブジェクトを切断したことを確認してください。

SQL Server で削除されたデータは、トランザクション ロールバック (コミットされていないトランザクションのロールバック) を通じて復元できます。データベース ログ (ログからデータを復元)。 SQL Server のネイティブ バックアップ (バックアップからデータベースを復元)。サードパーティの回復ツール (高度なテクノロジーを使用してデータを回復します)。 Microsoft サポートにお問い合わせください (専用のヘルプが必要です)。

削除が不完全なために SQL Server を再インストールできない問題は、次の手順に従って解決できます: ファイルとレジストリ エントリを手動で削除する; SQL Server のインストールおよびアンインストール ツールを使用する; サードパーティのアンインストール ツールを使用する; Windows イベント ビューアを確認する; を再起動するコンピューター; SQL Server を再インストールします。

Hibernate ポリモーフィック マッピングは、継承されたクラスをデータベースにマップでき、次のマッピング タイプを提供します。 join-subclass: 親クラスのすべての列を含む、サブクラス用の別個のテーブルを作成します。 table-per-class: サブクラス固有の列のみを含む、サブクラス用の別個のテーブルを作成します。 Union-subclass: join-subclass と似ていますが、親クラス テーブルがすべてのサブクラス列を結合します。
