What's new

[C# Windows Form Application] How can a database be programmed by code?

  • Thread starter Speeder2k
  • Start date
  • Views 435
S

Speeder2k

Newbie
Messages
3
Reaction score
0
How can a database be made programmatically? In VS 2012 I'm trying to make it so when a button is pressed it will check a certain file path if there's a database that exists. If not I wanted the database to be created. Can someone help me?
 
J

Joshy

Legend
Messages
7,172
Reaction score
4,978
How can a database be made programmatically? In VS 2012 I'm trying to make it so when a button is pressed it will check a certain file path if there's a database that exists. If not I wanted the database to be created. Can someone help me?

Have you tried this yet?

Sample

' Handles the click event for the Create Database button.
Private Sub btnCreateDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateDB.Click

' If the "Create Table" button is enabled this means the user is trying to
' recreate the database again in the same application run. Warn the user of
' how this will affect things, and if they want to proceed, reset the UI to
' the initial state so that errors are not induced if currently enabled
' buttons are clicked out of order.
If btnCreateTable.Enabled Then
Dim dr As DialogResult = MessageBox.Show("Recreating the database " & _
"will undo the other database object creation steps you have " & _
"made so far. Do you wish to proceed?", "Database Re-creation " & _
"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)

If dr = Windows.Forms.DialogResult.Yes Then
ResetUI()
CreateDatabase()
End If
Else
CreateDatabase()
End If

End Sub
Or this method:

To create the database, follow these steps:
  1. Create a new Visual C# .NET Windows application.
  2. Place a button on Form1. Change the button's Name property to btnCreateDatabase, and then change the Text property to Create Database.
  3. Use the using statement on the System and System.Data namespaces so that you do not have to qualify declarations in those namespaces later in your code. Add the following code to the General Declarations section of Form1:
    using System;
    using System.Data.SqlClient;
  4. Switch to Form view, and then double-click Create Database to add the click event handler. Add the following sample code to the handler:
    String str;
    SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

    str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

    SqlCommand myCommand = new SqlCommand(str, myConn);
    try
    {
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception ex)
    {
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    finally
    {
    if (myConn.State == ConnectionState.Open)
    {
    myConn.Close();
    }
    }


5. Change the connection string to point to your computer running SQL Server, and then verify that the Database argument is set to Master or is blank
6. Press F5 or CTRL+F5 to run the project, and then click Create Database
7. Use the Server Explorer to verify that the database is created.
I'm sure someone around here can help you with more.....
 
S

Speeder2k

Newbie
Messages
3
Reaction score
0
Have you tried this yet?

Sample



Or this method:
I tried everything on Google and I already tried the website you got the code from. It crashes and gives me a bunch of errors about the .Open() function.
 
O

OrCl_BaSiKz

Enthusiast
Messages
34
Reaction score
19
I tried everything on Google and I already tried the website you got the code from. It crashes and gives me a bunch of errors about the .Open() function.
Are you still looking for help
 
L

Lipton01

Enthusiast
Messages
92
Reaction score
18
I tried everything on Google and I already tried the website you got the code from. It crashes and gives me a bunch of errors about the .Open() function.
do you want an offline data base or an online data base if so you can just make a file and store it within the application and have the application read that file on launch.
 
M

Mnx

¿♤? °《Bot》°
Messages
1,731
Reaction score
1,617
This? Just add into button function. Should check if database exists.


C#:
using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("GET"), "URL HERE"))
    {
        var response = await httpClient.SendAsync(request);
    }
}

To create a new database


C#:
private void CreateDatabase(DatabaseParam DBParam)
{
    System.Data.SqlClient.SqlConnection tmpConn;
    string sqlCreateDBQuery;
    tmpConn = new SqlConnection();
    tmpConn.ConnectionString = "SERVER = " + DBParam.ServerName +
                         "; DATABASE = master; User ID = sa; Pwd = sa";
    sqlCreateDBQuery = " CREATE DATABASE "
                       + DBParam.DatabaseName
                       + " ON PRIMARY "
                       + " (NAME = " + DBParam.DataFileName +", "
                       + " FILENAME = '" + DBParam.DataPathName +"', "
                       + " SIZE = 2MB,"
                       + " FILEGROWTH =" + DBParam.DataFileGrowth +") "
                       + " LOG ON (NAME =" + DBParam.LogFileName +", "
                       + " FILENAME = '" + DBParam.LogPathName + "', "
                       + " SIZE = 1MB, "
                       + " FILEGROWTH =" + DBParam.LogFileGrowth +") ";
     SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
     try
     {
         tmpConn.Open();
         MessageBox.Show(sqlCreateDBQuery);
         myCommand.ExecuteNonQuery();
         MessageBox.Show("Database has been created successfully!",
                           "Create Database", MessageBoxButtons.OK,
                                       MessageBoxIcon.Information);
      }
     catch (System.Exception ex)
     {
         MessageBox.Show(ex.ToString(), "Create Database",
                                     MessageBoxButtons.OK,
                              MessageBoxIcon.Information);
     }
     finally
     {
         tmpConn.Close();
     }
     return;
}
 
Last edited:
Top Bottom