I've spent a lot of time trying to research outside resources, but different solutions seem to be more involved than I was hoping.
I am trying to achieve the following:
create simple database on existing SQL instance on this local computer.
security should just be a simple user name and password
other options are unnecessary (log, growth, max size, etc)
This is my first attempt at database integration with my program. using SQLite or SMO seemed slightly overwhelming to start. I've been trying to modify this sample code to work:
private void createDatabase()
{
String str;
SqlConnection myConn = new SqlConnection("Server=" + serverName + ";Integrated security=SSPI;database=master");
str = "CREATE DATABASE " + dbName + " ON PRIMARY " +
"(NAME = " + dbName + "_Data, " +
"FILENAME = 'C:\\" + dbName + ".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " + dbName + "_Log, " +
"FILENAME = 'C:\\" + dbName + ".ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
Any ideas on how to create a simple query string or something to create a database? If there's a better way, that's fine but keep in mind I'm trying to keep it as simple as possible just to start with.
Using SMO:
Server server = new Server("servername");
Database db = new Database(server, "MyDatabaseName");
db.Create();
To build an SMO application, you need to reference the SMO assemblies. Click ‘Add Reference’ and navigate to the folder
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies
Add references to these assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
Add this using statement to the file containing the above code:
using Microsoft.SqlServer.Management.Smo;
On a Side Note:
Fixing Slow SQL Server Management Objects (SMO) Performance
Related
I am creating a client in WPF with C # , and I need to install it on the client ( tablet surface ) . That said , I installed SQL Server 2014 Express edition , just to get the instance , I've downloaded from here :
https://www.microsoft.com/en-US/download/details.aspx?id=42299
and i get this:
Express 64BIT\SQLEXPR_x64_ENU.exe
I installed everything, of course I do not have the managament of SQL Server interface , but I can not create the db , here is my error:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server
this is my connection string (get this from constants file):
Server=SQLEXPRESS;Database=master;Integrated security=true;
and this is my code:
public void CreateDatabase(String PID)
{
String connection = Constants.localServerConnectionSQL.LocalServerConnectionSQLName;
SqlConnection Connection = new SqlConnection();
Connection = new SqlConnection(connection);
Connection.Open();
string Path = Environment.GetEnvironmentVariable("LocalAppData") + #"\CDA\UserDatabase\" + PID.ToString();
log.Info("DBCreationScripts: Path DB: " + Path.ToString());
String str = "CREATE DATABASE [" + PID + "] ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + Path + ".mdf', " +
"SIZE = 5MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = [" + PID + "Log_Log], " +
"FILENAME = '"+Path+"Log.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
log.Info("DBCreationScripts: Comando di creazione DB: " + str);
try
{
SqlCommand myCommand = new SqlCommand(str, Connection);
log.Info("DBCreationScripts: Lancio il comando di creazione database");
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
log.Info("DBCreationScripts: Eccezione nel comando di creazione database - Message: " + ex.Message);
throw ex;
}
}
The problem is that it fails to open the connection , the instance is SQLEXPRESS , but do not understand why colleagues are not . E ' can I have configured something wrong ?
The SQL services are all active .
Tips ?
The correct way to refer to a SQL Server instance is Server Address\Instance Name, eg MyServer\SQLExpress, .\SQLEXPRESS or 127.0.0.1\SQLEXPRESS.
Without the backslash, the text is interpreted as the machine name. A connection string with Server=SQLEXPRESS will try to connect to a server named SQLEXPRESS.
Beginner's question - please can I ask for advice on creating local database files programmatically at run time. I want to be able later to rename, delete them etc using Windows Explorer in the same way as for text and other files, and to copy them to other computers.
This is using Visual Studio Community 15 with C#, installed SQL server Data Tools 14.0.50616.0. The computer has Microsoft SQL Server 2014.
For an example I have removed the surplus parts of my program to leave the code below, which uses a Windows Form Application with 3 buttons (btnCreateDb, btnDeleteDb, and btnDoesDbExist) and a combobox cbxDb for the database name. It makes databases in an existing folder C:\DbTemp.
It will apparently create and delete a new database and make files, for example mydb1.mdf and mydb1.ldf in the folder, and state that they exist. However, if I delete the two files using Explorer, it throws an exception if an attempt is made to delete or to create the database; and btnDoesDbExist shows that it still exists.
Why does the database still appear to exist when the files have been deleted by Windows Explorer? The code under btnDoesDatabaseExist doesn't refer to the path of the files, so it must be seeing something else, but where? Is this a correct method for the user of the program to create, delete, and detect these databases?
using System;
using System.Data;
using System.Windows.Forms;
//my additions
using System.Data.SqlClient;
namespace DataProg15
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string form1ConnectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; Integrated Security = True; Connect Timeout = 30; ";
private string form1DatabasePath = "C:\\DbTemp";
private void btnCreateDb_Click(object sender, EventArgs e)
{
string nameToCreate = cbxDb.Text;
SqlConnection myConn = new SqlConnection(form1ConnectionString);
string str = "CREATE DATABASE " +nameToCreate+ " ON PRIMARY " +
"(NAME = " +nameToCreate+ "_Data, " +
"FILENAME = '" +form1DatabasePath+ "\\" +nameToCreate+ ".mdf', " +
"SIZE = 4MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " +nameToCreate+ "_Log, " +
"FILENAME = '" +form1DatabasePath+ "\\" +nameToCreate+ ".ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase '" + nameToCreate + "' was created successfully");
}
catch (System.Exception ex)
{
MessageBox.Show("Exception in CreateDatabase " + ex.ToString(), "Exception in CreateDatabase", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
private void btnDeleteDb_Click(object sender, EventArgs e)
{
string nameToDelete = cbxDb.Text;
string myConnectionString = form1ConnectionString + "AttachDBFileName = " + form1DatabasePath + "\\" + nameToDelete + ".mdf ";
string str = "USE MASTER DROP DATABASE " + nameToDelete;
SqlConnection myConn = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(str, myConn);
myConn.Open();
try
{
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase '" + nameToDelete + "' was deleted successfully");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception in DeleteDatabase '" +nameToDelete+ "'", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
private void btnDoesDbExist_Click(object sender, EventArgs e)
{
string nameToTest = cbxDb.Text;
using (var connection = new SqlConnection(form1ConnectionString))
{
using (var command = new SqlCommand(string.Format(
"SELECT db_id('" +nameToTest+ "')", nameToTest), connection))
{
connection.Open();
if ((command.ExecuteScalar() != DBNull.Value))
{
MessageBox.Show("DataBase '" +nameToTest+ "' exists");
}
else
{
MessageBox.Show("Database '" +nameToTest+ "' does not exist");
}
}
}
}
}
}
Thank you to all for replies, and your trouble is greatly appreciated.
I now understand that I'm using the wrong database so I've tried to use SQL Server Compact instead. Have uninstalled, downloaded again, and reinstalled SQL Server Compact including SP1. Have also downloaded and installed SQL Server Compact/SQLite Toolbox from https://visualstudiogallery.msdn.microsoft.com/0e313dfd-be80-4afb-b5e9-6e74d369f7a1 . But Visual Studio has throughout shown an error when I type using System.Data.SqlServerCe . Also when I type SqlCeEngine or SqlCecommand, I assume for the same reason.
In Visual Studio, SQL Server Data Tools and SQL Server Compact & SQLite Toolbox are shown as installed products, but not SQL Server Compact. Do I need to install this into Visual Studio, and if so how is it done?
In Solution Explorer under References, check that System.Data.SqlServerCe is listed. If not, right click on References then Add Reference -> Browse button and select the file System.Data.SqlServerCe.dll, probably in C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Desktop. System.Data.SqlServerCe should now appear under References.
The program below appears to work, and is much simpler. Thanks to all for assistance.
using System;
using System.Data;
using System.Windows.Forms;
//my additions
using System.Data.SqlServerCe;
using System.IO;
namespace DataProg15
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string form1DatabasePath = "C:\\DbTemp\\dbtemp1.sdf";
public static string form1ConnectionString = "Data Source = " +form1DatabasePath;
private void btnCreateDb_Click(object sender, EventArgs e)
{
SqlCeEngine engine = new SqlCeEngine(form1ConnectionString);
try
{
engine.CreateDatabase();
MessageBox.Show("DataBase '" +form1DatabasePath+ "' was created successfully");
}
catch (System.Exception ex)
{
MessageBox.Show("Exception in CreateDatabase " + ex.ToString(), "Exception in CreateDatabase", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
engine.Dispose();
}
}
private void btnDeleteDb_Click(object sender, EventArgs e)
{
if (File.Exists(form1DatabasePath))
{
try
{
File.Delete(form1DatabasePath);
MessageBox.Show("DataBase '" +form1DatabasePath+ "' was deleted successfully");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception in DeleteDatabase '" +form1DatabasePath+ "'", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void btnDoesDbExist_Click(object sender, EventArgs e)
{
if (File.Exists(form1DatabasePath))
{
MessageBox.Show("DataBase '" +form1DatabasePath+ "' exists");
}
else
{
MessageBox.Show("DataBase '" +form1DatabasePath+ "' does not exist");
}
}
}
}
SQL Server will not let you delete the physical files of a database if that database is active - EVER. The only you would ever be able to do this is if the database is DETACHED ( as mentioned earlier )
So I suspect something your telling us isn't quite right ??
I would change your "check database exists" logic to be;
select * from sys.databases where name = 'yourdatabasename'
I would run this query anyway when you have deleted your database, just to see what it returns.
I have created C# code which creates a .mdf SQL Server database file and this code works just fine.
There only few options are missing.
Especially I need to choose
either database "Recovery model" is full mode or simple mode and
either "Auto shrink" value is true or false during during creation of a database!
Code:
private void buttonCreateData_Click(object sender, EventArgs e)
{
String CreateDatabase;
SqlConnection connection = new SqlConnection("Server=(localdb)\\Projects;Integrated security=SSPI;database=master");
CreateDatabase = "CREATE DATABASE " + textBoxDataName.Text + " " +
"ON PRIMARY " +
"(NAME = '" + textBoxDataName.Text + "', " +
"FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".mdf', " +
"SIZE = 6MB, MAXSIZE = 4GB, FILEGROWTH = 10%) " +
"LOG ON " +
"(NAME = '" + textBoxDataName.Text + "_LOG" + "', " +
"FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".ldf', " +
"SIZE = 1MB, MAXSIZE = 200MB, FILEGROWTH = 10%)" +
"";
SqlCommand command = new SqlCommand(CreateDatabase, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Database is created successfully", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Remember I don't need to create the database firstly and then modify those two options. I need to set those two options during creation of database.
So what should I add in that code, I mean what kind of statement is missing in order to choose those two options during real-time?
I'm currently finishing an asp.net project for a class and began to notice a major flaw with one of the requisites. The application should ask five questions and write the answers to a database, afterwards it should display the results of the survey to the user.
This is what I have attempted so far:
public static string GetConnectionString()
{
string connStr = String.Format("server={0}; user id={1}; password={2};" + "database= -table to be accessed-; pooling=false",
"-database server-", "-user-", "-password-");
return connStr;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string sex = gender.Text;
string likes = interests.Text;
string edu = education.Text;
string nation = nationality.Text;
string userage = age.Text;
MySql.Data.MySqlClient.MySqlConnection mycon;
mycon = new MySqlConnection(GetConnectionString());
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
cmd.ExecuteNonQuery();
mycon.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mycon.Close();
}
}
}
I went ahead and replaced the database information with placeholders.
The database is MySql and hosted on an external server.
The issue I'm experiencing is that the code compiles, however the information does not get written to the database. I'm not certain if this is due to the fact that I'm still testing the code and have not uploaded the web application to the server or the fact that it's just wrong.
As far as displaying the results go, if the above code is correct it would simply be a matter of changing the sql query, correct?
Thanks in advance for the insight.
You are executing the command before opening database connection.
ExecuteNonQuery() method and all other Execute method require an open database connection.
And another error is:
Number of columns (i.e. 5) and provided values (i.e. 4) are not equal.
And one more issue in your code is here as stated by Steve Wellens.
Change Your Code like below:
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
mycon.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mycon.Close();
}
Security Notes:
Never add data into query using + operator. It may cause SQL Injection.
What if a user enters 1); DROP TABLE <table-name> -- in Age TextBox..??
Anyone can delete any table entirely from database.
Use MySQL Parameter to avoid such problems. It may prevent from causing serious damages to your entire database.
In your connection string:
"database= -table to be accessed-;
...you don't put the table. The table is specified in the SQL statement.
you should open the connect first, then execute the query.
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
mycon.Open();
cmd.ExecuteNonQuery();
}
This is likely not the only problem, but it is a problem:
"INSERT INTO survey (gender, age, birthplace, occupation, winner) " +
"VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')",
(I've broken it into two strings to make it easier to read.)
You are inserting into five columns. You are only specifying four data values, and with the exception of gender they don't appear to be in the right order or even be the right data.
try checking these things :
try opening your connection before executing the SQL
check your SQL, and try execute them directly against the database. what i see in your SQL is you are concatenating the values into one string (quotes exist only in beginning and end, but not in between the parameters passed)
we know that when we use ado.net then we can create database or table at run time programatically like
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();
}
}
so i am learning LINQ and EF. so i am interested to know that can i create table or database at runtime with the help of LINQ or EF. please let me know and if possible then please give me some link of good article with similar subject.
thanks
Tridip