1. 程式人生 > >C#建立資料庫,匯入sql指令碼

C#建立資料庫,匯入sql指令碼

/// <summary>
/// 建立資料庫
/// </summary>
/// <param name="connStr">連線字串</param>
/// <param name="_strDBName">資料庫名稱</param>
/// <returns></returns>
private static bool CreateDatabase(string connStr, string _strDBName)
{
	bool bSuccess = false;
	try
	{
		using (SqlConnection conMaster = new SqlConnection(connStr))
		{
			conMaster.Open();

			// Check if the Database has existed first
			string strExist = @"select * from dbo.sysdatabases where name='" + _strDBName + @"'";
			SqlCommand cmdExist = new SqlCommand(strExist, conMaster);
			SqlDataReader readerExist = cmdExist.ExecuteReader();
			bool bExist = readerExist.HasRows;
			readerExist.Close();
			if (bExist)
			{

				string strDel = @"drop database " + _strDBName;
				SqlCommand cmdDel = new SqlCommand(strDel, conMaster);

				cmdDel.ExecuteNonQuery();
			}

			// Create the database now;                   
			string strDatabase = "Create Database [" + _strDBName + "]";
			SqlCommand cmdCreate = new SqlCommand(strDatabase, conMaster);
			cmdCreate.ExecuteNonQuery();

			conMaster.Close();
		}

		bSuccess = true;
	}
	catch (Exception e)
	{
		throw e;
	}

	return bSuccess;
}
/// <summary>
/// 匯入sql指令碼
/// </summary>
/// <param name="sqlConnString">連線資料庫字串</param>
/// <param name="varFileName">指令碼路徑</param>
/// <returns></returns>
private static bool ExecuteSqlFile(string sqlConnString, string varFileName)
{
	if (!File.Exists(varFileName))
	{
		return false;
	}
	StreamReader rs = new StreamReader(varFileName, System.Text.Encoding.Default);
	ArrayList alSql = new ArrayList();
	string commandText = "";
	string varLine = "";
	while (rs.Peek() > -1)
	{
		varLine = rs.ReadLine();
		if (varLine == "")
		{
			continue;
		}
		if (varLine != "GO")
		{
			commandText += varLine;
			commandText += "\r\n";
		}
		else
		{
			commandText += "";
		}
	}
	alSql.Add(commandText);
	rs.Close();
	try
	{
		ExecuteCommand(sqlConnString, alSql);
		return true;
	}
	catch (Exception ex)
	{
		throw ex;
	}
}

private static void ExecuteCommand(string sqlConnString, ArrayList varSqlList)
        {
            using (SqlConnection conn = new SqlConnection(sqlConnString))
            {
                conn.Open();
                //Don't use Transaction, because some commands cannot execute in one Transaction.
                //SqlTransaction varTrans = conn.BeginTransaction();
                SqlCommand command = new SqlCommand();
                command.Connection = conn;
                //command.Transaction = varTrans;
                try
                {
                    foreach (string varcommandText in varSqlList)
                    {
                        command.CommandText = varcommandText;
                        command.ExecuteNonQuery();
                    }
                    //varTrans.Commit();
                }
                catch (Exception ex)
                {
                    //varTrans.Rollback();
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
        }

不用sqlcmd,因為它有很多侷限性。

相關推薦

C#建立資料庫匯入sql指令碼

/// <summary> /// 建立資料庫 /// </summary> /// <param name="connStr">連線字串</param> /// <param name="_strDBName">

centos下mysql新增使用者操作資料庫匯入sql檔案

1:檢視當前的使用者 select Host,User,Password from mysql.user; 查詢結果: +-------------------------+------+------------------------------------------

PostgreSQL 9.2 建立資料庫匯入和匯出資料庫建立超級使用者

一、首先要在cmd介面cd到資料庫的bin目錄下  1、查詢bin目錄路徑           (1) 開啟服務       (2)右鍵資料庫服務屬性 屬性介面裡面的可執行檔案的路徑就是資料庫bin目錄的路徑。   2、cd到bin目錄 3、建立超級

C#】EF學習<二> DbFirst (先建立資料庫表及其關聯關係)

工程壓縮檔案放到百度雲盤---20181019001資料夾   1. 建立表的指令碼   create table Teacher ( TID char(12) primary key, Tname char(6) not null ) create table

使用powerdesigner匯入sql指令碼生成物理模型

  有些時候我們的powerdesigner以jdbc的形式連結本地資料庫可能會失敗,這時候我覺得從sql檔案中生成物理模型是個很不錯的方法 1.開啟powerdesigner,檔案->->reverse engineer->->database   &

使用powerdesigner匯入sql指令碼生成物理模型name和code都顯示英文的解決方法

1.使用powerdesigner匯入sql指令碼,生成物理模型,步驟如下: 選擇相應的資料庫 選擇指令碼檔案 成功後,表名和欄位名都顯示英文,comment並沒有顯示。 解決方法:執行一段指令碼即可,步驟如下:  指令碼如下: --------------

建立資料庫然後建立表空間、建使用者、授權、用IMP匯入DMP檔案

1.最近做專案,要匯入Oracle的dmp檔案,很多年前用過oracle,該用的技術隨著時間都忘記的差不多了,現在標記在此,以免再次遇到同樣的問題而感到無措。 匯入dmp檔案,需要知道這個dmp檔案建立的使用者。因此需要先建立使用者,並授權給它。 (1)使用者的建立 首先,以system使用者登入Orac

Oracle——建立使用者、工作空間以及匯入sql指令碼

我這預設的是用system進來的,然後自己新建了一個使用者叫drp1,密碼也是drp1. create user drp1 identified by drp1; 一般資料庫都會給使用者一個預設的工作空間就是users,可以根據命令檢視 select

Oracle 建立資料庫使用者表空間資料匯入

以oa為例: 1 建立oa資料庫。字符集為utf-8。 2 prompt '建立LOGIN---oa'create user oa IDENTIFIED BY oa;GRANT ALTER ANY CLUSTER TO oa WITH ADMIN OPTION;GRANT ALTER ANY INDEX TO

Java實現資料庫備份並利用ant匯入SQL指令碼

開發十年,就只剩下這套架構體系了! >>>   

MySQL必知必會-官方資料庫表及SQL指令碼匯入生成

最近在複習SQL語句,看的是MySQL必知必會這本書,但是發現附錄中只有表設計,沒有表的具體資料。所以在學習相應的語句中體驗不是很好,去網上查了資料庫的內容,自己慢慢匯入到了資料庫中。把表放出來作為參照,SQL指令碼語句放在最後,可以直接導到自己的資料庫。 customer表 cust_idcust_

VS2013 c++連結資料庫應用儲存過程資料庫中寫入資料

// ConsoleApplication1.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include "iomanip" using namespace std; #import "c:\Program Files\Common Files\S

php向資料庫匯入.sql檔案

<?php     function insert($file,$database,$name,$root,$pwd)//     {         //將表匯入資料庫      

【mysql】mysql建立資料庫基字符集 和 資料庫排序規則 的對比選擇

1.一般選擇utf8.下面介紹一下utf8與utfmb4的區別。 utf8mb4相容utf8,且比utf8能表示更多的字元。至於什麼時候用,看你的做什麼專案了,到https://www.cnblogs.com/sxdcgaq8080/p/9932786.html看unicode編碼區從1 ~ 126就屬於傳

sugarORM建立資料庫建立

1.先對程式進行環境的配置,首先在build.gradle中匯入相關包,程式碼如下: 2.然後AndroidManifest.xml中的application 中新增標籤,程式碼如下,其中test.db表示所要建立的資料庫名,1表示版本號,true表示是否允許SugarORM記錄log,c

Oracle表的建立.表空間建立刪除匯入匯出等

建立表空間; 先在E盤建立oradate再在裡面建一個temp, 再開啟命令列cmd在寫入sqlplus再寫入sys/[email protected] as sysdba再寫入 create tablespace FUNDS5DAT logging datafile 'E

CentOS7下編寫建立使用者刪除使用者指令碼

剛開始學shell程式設計,自己寫兩個指令碼玩玩 建立使用者: 1 #!/bin/bash 2 useradd $1

docker 部署mysql服務之後執行sql指令碼

1,先將.sql檔案copy到docker容器裡 docker ps //找到容器的短ID或者指定的name。 docker inspect  -f '{{.Id}}' id or name 得到指定容器的全ID docker cp 本地檔案路徑 ID全稱:容器路徑[d

MySQL Workbench 匯入sql指令碼

最近一直在搞資料,資料量大了真的很頭疼。特別是資料遷移,用的是insert的sql指令碼。 匯入資料方法一: 主頁面上有這個按鈕,意思大開啟sql指令碼。按鈕如下: 點選按鈕選擇指令碼: 選擇指令碼

Navicat 匯入sql指令碼檔案

我在組建自己工作用的資料庫時要匯入.sql指令碼檔案,用cmd視窗匯入太慢,navicat的匯入嚮導裡又無匯入sql指令碼的選項, 但不是navicat中沒有匯入sql指令碼檔案的方法,只是要選擇資料庫右擊執行sql指令碼檔案便可以快速匯入sql指令碼的資料。主要操作步