欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#创建数据库及附加数据库的操作方法

程序员文章站 2023-11-08 15:05:58
本文实例讲述了c#创建数据库及附加数据库的操作方法。分享给大家供大家参考,具体如下: /// /// 附加数据库方法 ///...

本文实例讲述了c#创建数据库及附加数据库的操作方法。分享给大家供大家参考,具体如下:

/// <summary>
/// 附加数据库方法
/// </summary>
/// <param name="strsql">连接数据库字符串,连接master系统数据库</param>
/// <param name="dataname">数据库名字</param>
/// <param name="strmdf">数据库文件mdf的路径</param>
/// <param name="strldf">数据库文件ldf的路径</param>
/// <param name="path">安装目录</param>
private  void createdatabase( string strsql, string dataname, string strmdf, string strldf, string path)
{
  sqlconnection myconn = new sqlconnection(strsql);
  string str = null ;
  try
  {
   str = " exec sp_attach_db @dbname='"+dataname+"',@filename1='"+strmdf+"',@filename2='"+strldf+"'";
   sqlcommand mycommand = new sqlcommand(str, myconn);
   myconn.open();
   mycommand.executenonquery();
   messagebox.show("数据库安装成功!点击确定继续");//需using system.windows.forms
  }
  catch(exception e)
  {
   messagebox.show("数据库安装失败!" + e.message+"\n\n"+"您可以手动附加数据");
   system.diagnostics.process.start(path);//打开安装目录
  }
  finally
  {
   myconn.close();
  }
}
public override void install(system.collections.idictionary statesaver)
{
  string server = this.context.parameters["server"];//服务器名称
  string uid = this.context.parameters["user"];//sqlserver用户名
  string pwd = this.context.parameters["pwd"];//密码
  string path = this.context.parameters["targetdir"];//安装目录
  string strsql = "server=" + server + ";uid=" + uid + ";pwd=" + pwd + ";database=master";//连接数据库字符串
  string dataname = "jxc";//数据库名
  string strmdf = path + @"jxc.mdf";//mdf文件路径,这里需注意文件名要与刚添加的数据库文件名一样!
  string strldf = path + @"jxc_log.ldf";//ldf文件路径
  base.install(statesaver);
  this.createdatabase(strsql, dataname, strmdf, strldf, path);//开始创建数据库
}
/// <summary>
/// 测试连接
/// </summary>
/// <param name="servername"></param>
/// <param name="dbname"></param>
/// <param name="username"></param>
/// <param name="password"></param>
private sqlconnection testconnection(string servername, string dbname, string username, string password)
{
    string connectionstring = getconnectionstring(servername, dbname, username, password);
    sqlconnection connection = new sqlconnection(connectionstring);
    try
    {
      if (connection.state != connectionstate.open)
      {
        connection.open();
      }
      return connection;
    }
    catch
    {
      closeconnection(connection);
      throw new installexception("安装失败!\n数据库配置有误,请正确配置信息!");
    }
}
/// <summary>
/// 得到连接字符串
/// </summary>
/// <param name="servername"></param>
/// <param name="dbname"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
private string getconnectionstring(string servername, string dbname, string username, string password)
{
    string connectionstring = "data source={0};initial catalog={1};user id={2};password={3}";
    connectionstring = string.format(connectionstring, servername, dbname, username, password);
    return connectionstring;
}
/// <summary>
/// 创建数据库
/// </summary>
/// <param name="servername"></param>
/// <param name="dbname"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="connection"></param>
/// <param name="statesaver"></param>
public int createdatabase(sqlconnection connection)
{
    int result = -1;
    connection.changedatabase("master");
    string createdbsql = @" if exists(select 1 from sysdatabases where [name]=n'{0}')
        begin
        drop database {0}
        end
        go
        create database {0} ";
    createdbsql = string.format(createdbsql, _dbname);
    //因为有go在sqlcommand中不认识,所以以go为分隔符取sql语句
    char[] split = new char[] { 'g', 'o' };
    string[] sqllist = createdbsql.split(split);
    sqlcommand command = null;
    try
    {
      command = connection.createcommand();
      command.commandtype = system.data.commandtype.text;
      foreach (string sqlitem in sqllist)
      {
        if (sqlitem.length > 2)
        {
          command.commandtext = sqlitem;
          result = command.executenonquery();
        }
      }
      return result;
    }
    catch
    {
      closeconnection(connection);
      command.dispose();
      throw new installexception("安装失败!\n数据库配置不正确!");
    }
}
/// <summary>
/// 分隔sql语句
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
private string[] splitsql(string sql)
{
    regex regex = new regex("^go", regexoptions.ignorecase | regexoptions.multiline);
    string[] sqllist = regex.split(sql.toupper());
    return sqllist;
}

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。