经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
C# 动态创建SQL数据库
来源:cnblogs  作者:永恒921  时间:2018/12/19 9:14:34  对本文有异议

最近在做项目中要求能够要求动态添加数据库并建表。具体思路如下

1 提供数据名,根据数据库创建数据库

2 自定数据库与数据表,提供数据表自定与数据类型创建表

 

创建sqlhelper类,用于数据库操作

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Text;
  7.  
  8. /******************************************************************* 
  9. * Copyright (C)  版权所有
  10. * 文件名称:SqlHelper
  11. * 命名空间:TestRecentMenu
  12. * 创建时间:2018/12/18 14:26:01
  13. * 作    者: wangyonglai
  14. * 描    述:
  15. * 修改记录:
  16. * 修改人:
  17. * 版 本 号:v1.0.0
  18. **********************************************************************/
  19. namespace TestRecentMenu
  20. {
  21. public static class SqlHelper
  22. {
  23. /// <summary>
  24. /// 使用锁防止多线程同时操作数据库表
  25. /// </summary>
  26. private static readonly object sqlLock = new object();
  27.  
  28. /// <summary>
  29. /// SQL连接
  30. /// </summary>
  31. private static SqlConnection connection;
  32.  
  33. private static string connStr = "server=127.0.0.1; database=; user id=sa;password=Root123";
  34. /// <summary>
  35. /// 创建SQL连接属性
  36. /// </summary>
  37. public static SqlConnection Connection
  38. {
  39. get
  40. {
  41. try
  42. {
  43. if (connection == null)//如果没有创建连接,则先创建
  44. {
  45. //从配置文件中获取SQL连接字段
  46. //string connStr = ConfigurationManager.ConnectionStrings["ConnetcionNmae"].ToString();
  47.  
  48. connection = new SqlConnection(connStr);//创建连接
  49. connection.Open();//打开连接
  50. }
  51. else if (connection.State == ConnectionState.Broken)//如果连接中断,则重现打开
  52. {
  53. connection.Close();
  54. connection.Open();
  55. }
  56. else if (connection.State == ConnectionState.Closed)//如果关闭,则打开
  57. {
  58. connection.Open();
  59. }
  60. return connection;
  61. }
  62. catch (Exception ex)
  63. {
  64. if (connection != null)
  65. {
  66. connection.Close();
  67. connection.Dispose();
  68. }
  69. //Log4netHelper.WriteErrorLog("Connection" + ex.Message, ex);
  70. return null;
  71. }
  72. }
  73. }
  74.  
  75. /// <summary>
  76. /// 重置连接
  77. /// </summary>
  78. public static void ResetConnection()
  79. {
  80. if (connection != null)
  81. {
  82. connection.Close();
  83. connection.Dispose();
  84. connection = null;
  85. }
  86. }
  87.  
  88. /// <summary>
  89. /// 获取数据集
  90. /// </summary>
  91. /// <param name="str">执行字符串</param>
  92. /// <returns></returns>
  93. public static DataSet GetDataSet(string str)
  94. {
  95. lock (sqlLock)
  96. {
  97. try
  98. {
  99. SqlDataAdapter sda = new SqlDataAdapter(str, Connection);
  100. DataSet ds = new DataSet();
  101. sda.Fill(ds);
  102. return ds;
  103. }
  104. catch (Exception ex)
  105. {
  106. ResetConnection();
  107. //Log4netHelper.WriteErrorLog(str, ex);
  108. return null;
  109. }
  110. }
  111. }
  112.  
  113. /// <summary>
  114. /// 获取数据集
  115. /// </summary>
  116. /// <param name="str"></param>
  117. /// <param name="values"></param>
  118. /// <returns></returns>
  119. public static DataSet GetDataSet(string str, params SqlParameter[] values)
  120. {
  121. lock (sqlLock)
  122. {
  123. try
  124. {
  125. SqlCommand cmd = new SqlCommand();
  126. cmd.Connection = Connection;
  127. cmd.CommandText = str;
  128. cmd.Parameters.AddRange(values);
  129. SqlDataAdapter sda = new SqlDataAdapter();
  130. sda.SelectCommand = cmd;
  131. DataSet dt = new DataSet();
  132. sda.Fill(dt);
  133. return dt;
  134. }
  135. catch (Exception ex)
  136. {
  137. ResetConnection();
  138. //Log4netHelper.WriteErrorLog(str, ex);
  139. return null;
  140. }
  141. }
  142. }
  143.  
  144. /// <summary>
  145. /// 获取表格
  146. /// </summary>
  147. /// <param name="str">执行字符串</param>
  148. /// <returns></returns>
  149. public static DataTable GetDataTable(string str)
  150. {
  151. return GetDataSet(str).Tables[0];
  152. }
  153.  
  154. /// <summary>
  155. /// 获取表格
  156. /// </summary>
  157. /// <param name="str">执行字符串</param>
  158. /// <param name="values">参数值数组</param>
  159. /// <returns></returns>
  160. public static DataTable GetDataTable(string str, params SqlParameter[] values)
  161. {
  162. return GetDataSet(str, values).Tables[0];
  163. }
  164.  
  165.  
  166. /// <summary>
  167. /// 执行SQL语句
  168. /// </summary>
  169. /// <param name="str"></param>
  170. public static void ExecuteNonQuery(string str)
  171. {
  172. try
  173. {
  174. SqlCommand cmd = new SqlCommand();
  175. cmd.Connection = Connection;
  176. cmd.CommandType = CommandType.Text;
  177. cmd.CommandText = str;
  178. cmd.ExecuteNonQuery();
  179. }
  180. catch
  181. {
  182. }
  183. }
  184.  
  185. /// <summary>
  186. /// 执行sql语句
  187. /// </summary>
  188. /// <param name="str"></param>
  189. /// <returns></returns>
  190. public static bool ExecuteSql(string str)
  191. {
  192. lock (sqlLock)
  193. {
  194. SqlCommand cmd = new SqlCommand();
  195. cmd.Connection = Connection;
  196. SqlTransaction trans = Connection.BeginTransaction();
  197. try
  198. {
  199. if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Open)
  200. {
  201. cmd.Transaction = trans;
  202. cmd.CommandType = CommandType.Text;
  203. cmd.CommandText = str;
  204. cmd.ExecuteNonQuery();
  205. trans.Commit();
  206. return true;
  207. }
  208. else
  209. {
  210. return false;
  211. }
  212. }
  213. catch (SqlException ex)
  214. {
  215. trans.Rollback();//事物回滚
  216. //ResetConnection();
  217. //Log4netHelper.WriteErrorLog(str, ex);
  218. return false;
  219. }
  220. }
  221. }
  222.  
  223. /// <summary>
  224. /// 执行sql语句
  225. /// </summary>
  226. /// <param name="str"></param>
  227. /// <param name="values"></param>
  228. /// <returns></returns>
  229. public static bool ExecuteSql(string str, params SqlParameter[] values)
  230. {
  231. lock (sqlLock)
  232. {
  233. SqlCommand cmd = new SqlCommand();
  234. cmd.Connection = Connection;
  235. SqlTransaction trans = Connection.BeginTransaction();
  236. try
  237. {
  238. if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Open)
  239. {
  240. cmd.Transaction = trans;
  241. cmd.CommandText = str;
  242. cmd.Parameters.AddRange(values);
  243. cmd.ExecuteNonQuery();
  244. trans.Commit();
  245. return true;
  246. }
  247. else
  248. {
  249. return false;
  250. }
  251. }
  252. catch (SqlException ex)
  253. {
  254. trans.Rollback();//事物回滚
  255. ResetConnection();
  256. //Log4netHelper.WriteErrorLog(str, ex);
  257. return false;
  258. }
  259. }
  260. }
  261.  
  262. }
  263. }

  

编写调用函数

  1. /// <summary>
  2. /// 判断数据库是否存在
  3. /// </summary>
  4. /// <param name="db">数据库名称</param>
  5. /// <returns></returns>
  6. public Boolean IsDBExist(string db)
  7. {
  8. string createDbStr = " select * from master.dbo.sysdatabases where name " + "= '" + db + "'";
  9. DataTable dt = SqlHelper.GetDataTable(createDbStr);
  10. if (dt.Rows.Count > 0)
  11. {
  12. return true;
  13. }
  14. return false;
  15. }
  16.  
  17. /// <summary>
  18. /// 判断数据库中指定表格是否存在
  19. /// </summary>
  20. /// <param name="db"></param>
  21. /// <param name="tb"></param>
  22. /// <returns></returns>
  23. public Boolean IsTableExist(string db, string tb)
  24. {
  25. string createTbStr = "USE " + db + " select 1 from sysobjects where id =object_id('" + tb + "') and type = 'U'";
  26. DataTable dt = SqlHelper.GetDataTable(createTbStr);
  27. if (dt.Rows.Count > 0)
  28. {
  29. return true;
  30. }
  31. return false;
  32. }
  33.  
  34.  
  35. /// <summary>
  36. /// 创建数据库
  37. /// </summary>
  38. /// <param name="db"></param>
  39. public void CreateDataBase(string db)
  40. {
  41. if (IsDBExist(db))
  42. {
  43. throw new Exception("数据库已经存在!");
  44. }
  45. else//不存在则创建
  46. {
  47. string createDbStr = "Create DATABASE " + db;
  48. SqlHelper.ExecuteNonQuery(createDbStr);
  49. }
  50. }
  51.  
  52.  
  53. /// <summary>
  54. /// 创建数据库表
  55. /// </summary>
  56. /// <param name="db">数据库名</param>
  57. /// <param name="tb">表名</param>
  58. public void CreateDataTable(string db, string tb)
  59. {
  60. if (IsDBExist(db) == false)
  61. {
  62. throw new Exception("数据库不存在!");
  63. }
  64. if (IsTableExist(db, tb))
  65. {
  66. throw new Exception("数据库表已经存在!");
  67. }
  68. else
  69. {
  70. string content = "usseId int IDENTITY(1,1) PRIMARY KEY ,userName nvarchar(50)";
  71. string createTableStr = "USE " + db + " Create table " + tb + "(" + content + ")";
  72.  
  73. SqlHelper.ExecuteNonQuery(createTableStr);
  74. }
  75. }

  最后调用

 

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. try
  4. {
  5. CreateDataBase(database);
  6. }
  7. catch (Exception ex)
  8. {
  9. Console.WriteLine(ex.Message);
  10. }
  11. }
  12.  
  13. private void button2_Click(object sender, EventArgs e)
  14. {
  15. CreateDataTable(database, "usertb");
  16. }

  

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号