I haven't written this article for a long time. This time I encountered the following question: "No need to attach a database or modify the web. config is so troublesome. Instead, you can directly run a page and then guide the user step by step through the Wizard to install and generate a database. "To do this, you need a statement to create a database and a statement to create these database tables, there are also the statements for creating database views and functions. Create a database statement
"IF Not EXISTS (select name from master.dbo.sysdatabases where name = N'" + DataBaseName+ "') CREATE DATABASE " + DataBaseName
"Use [" + DataBaseName+ "];"
The cs file in asp.net can be executed just like an SQL statement.
How can I obtain the statement for creating a database? One method is to directly generate files in the design database, and the other method is obtained from the existing database. Select a database and click the reverse key.
Select the task generation script
In the dialog box popped up below, I believe that everyone will choose the option as needed. If you don't know it, don't worry about it. But pay attention to this page
First, select only the table, because only the execution statement of the table is required. A. SQL file can be generated. Name CreateTable. SQL
Then we can only read the character strings in CreateTable. SQL In the cs file and execute them like SQL statements.
StreamReader strRead = File. OpenText ("D: \ CareateTable. SQL ");
String strContent = strRead. ReadToEnd ();
StrRead. Close ();
SqlConnection con = new SqlConnection ();
Con = "connect to database string ";
SqlCommond com = new SqlCommond ();
Com. Connection = con;
Com. CommandTest = strContent;
Com. CommandType = CommandType. Text;
Con. Open ();
Try
{
Con. ExecuteNonQuery ();
}
Catch (Exception ex)
{
......
}
Finally
{
Conn. Close ();
}
An error is reported, that is, an error occurs near the go statement. You can use word to replace go with "". Then, when you run the program, you will find that the database table is created.
In this case, the database may contain stored procedures, views, and functions. This is what I encountered. In this case, you need to select all images on that particular graph. However, as I did above, I always report errors, but there is no error in SQL Execution. And finally solved the problem.
Process sqlprocess = new Process ();
Sqlprocess. StartInfo. FileName = "osql.exe ";
// U is the user name, P is the password, S is the ip address of the target server, and infile is the path of the database script
Sqlprocess. StartInfo. Arguments = String. Format ("-U {0}-P {1}-S {2}-I {3}-d {4 }",
"Sa", "asd123", "127.0.0.1", "D: \ CreateTable. SQL", DataBaseName );
Sqlprocess. Start ();
// Wait for the program to execute the. SQL script
Sqlprocess. WaitForExit ();
Sqlprocess. Close ();
Response. Write ("<script> alert ('OK.'); </script> ");
In this way, the. SQL file can be called in asp.net.