如何使用.net 4.0中的c#代码创建数据库 [英] How to create a database using c# code in .net 4.0

查看:137
本文介绍了如何使用.net 4.0中的c#代码创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





使用c#代码,我必须首先检查数据库是否存在,如果它不存在,我必须创建数据库。一旦DB存在,那么我需要使用c#代码本身创建几个表。



请回复。



谢谢和问候,

Mathi。

Hi,

Using c# code, I have to check whether a database exists or not first and if it doesn't exists I have to create the database. And once DB exists then I need to create few tables using the c# code itself.

Please reply.

Thanks & Regards,
Mathi.

推荐答案

试试这个

http://support.microsoft.com/kb/307283 [ ^ ]

http://www.c-sharpcorner.com/Forums/Thread/42411/ [ ^ ]

使用C#创建SQL Server数据库 [ ^ ]
try this
http://support.microsoft.com/kb/307283[^]
http://www.c-sharpcorner.com/Forums/Thread/42411/[^]
Create an SQL Server Database Using C#[^]






PLE请检查一下。



请更改加粗文字



Hi,

Please check this.

Please change the bolded text

string sqlCreateDBQuery;
    try
    {
        SqlConnection tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");

        sqlCreateDBQuery = "SELECT * FROM master.dbo.sysdatabases where name =
        \'Your db name\'";

        using (tmpConn)
        {
            tmpConn.Open();
            tmpConn.ChangeDatabase("master");

            using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
            {
                int exists = sqlCmd.ExecuteNonQuery();

                if (exists <= 0)
                {
                   string script = your db creating sql script;
                   sqlCmd.ExecuteNonQuery(script);
                }
                else
                {
                   string script = your tables creating sql script;
                   sqlCmd.ExecuteNonQuery(script);
                }
            }
        }
    }
    catch (Exception ex) { }


您好,

参考这些链接可能对您有帮助,

http://support.microsoft.com/kb/307283 [ ^ ]

使用C#创建SQL Server数据库 [ ^ ]
Hi,
Refer to these links may help you,
http://support.microsoft.com/kb/307283[^]
Create an SQL Server Database Using C#[^]


这篇关于如何使用.net 4.0中的c#代码创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆