How to create a Microsoft SQL Server database by using ADO.NET? - c#

How to create a Microsoft SQL Server database by using ADO.NET and Visual C# .NET programmatically?
I need to create databases programmatically.
I use this code but after creating database, I cannot add a table to this DB due to permission problem
string 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();
}
}
my code for Creating Table
string path="";// new DB path
string constring = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + path + ";Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True";
string qry="create table table1 ( ID int, name varchar(20) )";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();

According with your code, you created the database, so ... Before you call the command to create the table, Did you anytime add an "USE DATABASE [DataBaseName]" in your string variable? In my case, I've had to add this code to create the tables. Of course, you must note for the user's permissions of the connection string commented above.

Based on the error description, following steps may work. I assume that your SQL server runs on the same machine as your test program.
Create a worldwide writable directory (C:\mydbdir).
Let the DB file be created there (C:\mydbdir\MyDatabaseData.mdf)
Try to create the tables in the DB
As ta.speot.is noted, you are (very likely) missing write permissions to C:\ for SQL server process.

You created a database but you did not set the permissions to it.
So after database creation add:
var userName = "sa"; // username that is used in the connection
var str = String.Format("USE MyDatabase; EXEC sp_changedbowner '{0}'", userName);
Do a ExecuteNonQuery with this as well and then you have the rights to add tables, etc.
EDIT
Btw: Sidenote: I would just execute
USE master; IF ( NOT(SELECT IsNull(db_id('myDBname'),-1)>0) ) CREATE DATABASE 'myDBname'
and let the SQL server do the rest. Easier to create like this, but it is just another way how to do it.

Related

LocalDB changes persist in different mdf files - Why?

I am trying to rebuild an application that originally used sqlite to now use 'localdb'. (I want an application that can create its own database locally and at runtime without requiring a pre-installed instance of sql server or sql express on the target machine)
I want to move away from using a 'third party' library (sqlite) as experience has told me it can be a pain to get it working from scratch, and towards something supposedly more straightforward to get up and running from scratch.
Using code copied (and slightly modified) from the web I have managed to create an mdf file dynamically/programmatically, but I am puzzled by what happens if I run it more than once, even if I choose a new filename each time. Namely it seems to somehow keep the changes/additions made on each run. Below is the relevant code...
public partial class Form1 : Form
{
SqlConnection conn;
public void CreateSqlDatabase(string filename)
{
string databaseName =
System.IO.Path.GetFileNameWithoutExtension(filename);
conn = new SqlConnection(
String.Format(
#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"
));
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText =
String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')"
, databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CreateSqlDatabase(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText =
"create table mytable (id int, name nvarchar(100))";
comm.ExecuteNonQuery();
comm.CommandText =
"insert into mytable (id,name) values (10,'testing')";
comm.ExecuteNonQuery();
comm.CommandText = "select * from mytable";
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
textBox1.Text +=
reader["id"].ToString() + ", " + reader["name"].ToString() + "\r\n";
}
conn.Close();
}
}
If I run the app once It runs through fine.
If I run the app a second time, and choose a different filename for the database it tells me 'mytable' already exists.
If I comment out the create table code it runs, but the select query returns multiple rows indicating multiple inserts (one for each time the app runs)
I am just seeking to understand why this happens. Do I need to delete database/table each time if I want the app to behave as if it has created the database/table from scratch on each subsequent run?
You have initial catalog 'master' in your connection string. Are you sure you haven't created the tables in the master database instead of the newly created database?
After the creation & detach of the database file, you could try and change your connection to:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\xxx\xxx\xxx.mdf");

C# Unable to log data onto database

I am trying to log everytime a search is conducted on my program. The log is located on an access database. When i try to log the name of the user and computer name i receive an error and the data does not populate on my access database. Below is the code i have any support would be greatly appreciated.
private void logdata()
{
string User="";
string PCName="";
DateTime now = DateTime.Now;
User = WindowsIdentity.GetCurrent().Name.ToString();
PCName = SystemInformation.ComputerName.ToString();
try
{
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\data.accdb;Jet OLEDB:Database Password=test";
string cmdstr = "Insert into SearchLog(Location,SearchDate,SearchTime,User,PCName)Values(#a,#b,#c,#d,#e)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#a", txtLocNo.Text);
com.Parameters.AddWithValue("#b", now.ToString("d"));
com.Parameters.AddWithValue("#c", DateTime.Now.ToString("HH:mm:ss"));
com.Parameters.AddWithValue("#d", User);
com.Parameters.AddWithValue("#e", PCName);
com.ExecuteNonQuery();
con.Close();
}
catch (Exception eX)
{
string ErrorPrompt = "Select Ok and your search will continue";
MessageBox.Show(ErrorPrompt, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
USER is a keyword in MS-Access Jet SQL. If you have a field or a table with that name then you should enclose it in square brackets when passing a command text from an application.
string cmdstr = #"Insert into SearchLog(Location,SearchDate,SearchTime,[User],PCName)
Values(#a,#b,#c,#d,#e)";
I suggest, if this is possible, to change the name of that field to something different to avoid future errors of this kind.
Also keep in mind that AddWithValue creates the parameter with a datatype taken from the value part.
You have two fields that seems to be dates but you create a parameter of string type (ToString()).
OLE DB.NET Framework Data Provider uses positional parameters that are
marked with a question mark (?) instead of named parameters.
MSDN
see also https://stackoverflow.com/a/8124103/1271037

Struggling to insert record into "SQL Server Compact 4.0 Database" from my C# WinForm Application. (I'm using VS 2010))

In my C# Winform Application I have written a code to insert record into the "SQL Server Compact 4.0 Database". Also I had debug code line-by-line everything is working fine (without any error) but after insert functionality when I checked my database I found that record is not inserted into the database, I'm strange why it is happening..!
But I think it is happening because, "when I tried to add database in my project I got this error" Following is my code to insert record into the database--
// Retrieve the connection string from the settings file.
string conString = Properties.Settings.Default.snda_dbConnectionString;
//string conString = "Data Source=|DataDirectory|\\db_snda.sdf";
try
{
conString = conString +";Password = test#1;";
// Open the connection using the connection string.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
// Read in all values in the table.
using (SqlCeCommand cmd = new SqlCeCommand("INSERT INTO tbl_user_master" + "(user_id, password, user_type, user_title, first_name, middle_name, last_name, gender, dob, mobile_no, email_id, plant_code, div_code, region_code, reporting_to, releaving_date, created_date)" + " VALUES(#user_id, #password, #user_type, #user_title, #first_name, #middle_name, #last_name, #gender, #dob, #mobile_no, #email_id, #plant_code, #div_code, #region_code, #reporting_to, #releaving_date, #created_date)", con))
{
cmd.Parameters.AddWithValue("#user_title", strTitle);
cmd.Parameters.AddWithValue("#first_name", strFirstName);
cmd.Parameters.AddWithValue("#middle_name", strMiddleName);
cmd.Parameters.AddWithValue("#last_name", strLastName);
cmd.Parameters.AddWithValue("#gender", strGender);
cmd.Parameters.AddWithValue("#user_type", strUserType);
cmd.Parameters.AddWithValue("#plant_code", strPlantCode);
cmd.Parameters.AddWithValue("#div_code", strDivCode);
cmd.Parameters.AddWithValue("#region_code", strRegionCode);
cmd.Parameters.AddWithValue("#reporting_to", strReportingTo);
cmd.Parameters.AddWithValue("#user_id", strUserName);
cmd.Parameters.AddWithValue("#password", Encrypt(strPassword)); //Encrypt(strPassword)
cmd.Parameters.AddWithValue("#email_id", strEmailId);
cmd.Parameters.AddWithValue("#mobile_no", strMobileNo);
cmd.Parameters.AddWithValue("#dob", strDOB);
cmd.Parameters.AddWithValue("#created_date", strCreatedDate);
cmd.Parameters.AddWithValue("#releaving_date", strReleavingDate);
cmd.ExecuteNonQuery();
}
con.Close();
XtraMessageBox.Show("User Created Successfully.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
ResetAfterSubmit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Thank you...!
It is hapening because you mix up databases - the one you check is not the one that is used during insert as likely when you start the debugging of the program a copys created in the output folder - and then discarded when you stop the program.
This is not exactly a rare problem and a good indication of someone not using a search function to find a solution.

Issue with connectionString. Using Visual studio 2013 pro. trying to connect to employee DB on SQL Server 2012,

I am trying to connect to SQL Server 2012 express. There is a database called employee which I would like to save data from a WPF form to a table called [dbo].[EVUSERS]. It is stored in my local Database. From some examples I see that "Data Source=.\SQLEXPRESS" Is this correct? Or should I specify the table aswell? using localhost as the server doesn't work either.
I get an error saying "the server was not found or was not accessible."
Do I have to configure the server in some way to receive connections?
Here is my attempt.
void saveData()
{
try
{
var firstName = fNameTextbox.Text;
var lastName = LNameTextBox.Text;
var userName = UserName.Text;
String pass = PasswordTextBox.Password;
String confirm = ConfirmTextBox.Password;
int loggedIn = 1;
//parameterise values
string connectionString = #"Data Source=.\SQLEXPRESS;Database=Employee";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO [dbo].[EVUSERS] (UName, Pass, FName, LName, Attempts, LastLogin, LoggedIn) VALUES (#UName, #Pass, #FName, #LName, #Attempts, #LastLogin, #LoggedIn)";
command.Parameters.AddWithValue("#UName", UserName);
command.Parameters.AddWithValue("#Pass", pass);
command.Parameters.AddWithValue("#FName", firstName);
command.Parameters.AddWithValue("#LName", lastName);
command.Parameters.AddWithValue("#Attempts", attempts);
command.Parameters.AddWithValue("#LastLogin", lastLogIn);
command.Parameters.AddWithValue("#LoggedIn", loggedIn);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("command number of rows = " + command);
}
//connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is a screenshot of the server connection.
Many Thanks
.\SQLExpress is correct. If the database name is correct (although for SQL Express it should be a path to the file, yes?) then you can add ";Integrated Security=SSPI" to the connection string and you'll be OK if you are the user who installed it.
Can Use It For Connect With Sql Server 2012 :
var connectionString = "Server=127.0.0.1;DataBase=Employee;
User Id=(sa or your user id without Parenthesis);
Password=(your password without Parenthesis);";

How to backup from .mdf database that created by VS

I was created a .mdf database file with vs 2010. I can retrive and insert data into database bbut when i want to backup error was handled. that database not attach in Management Studio.
my Code :
SqlConnection connect;
connect = new SqlConnection(DAL.AccessLayerClass._connectionStr);
connect.Open();
SqlCommand command;
command = new SqlCommand(#"backup database AGMDB to disk ='d:\svBackUp1.bak' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
my connection string:
string _connectionStr = "Data Source=.\\SQLEXPRESS; AttachDbFilename=" + System.Windows.Forms.Application.StartupPath + "\\Database\\AGMDB.mdf; Integrated Security=True; Connect Timeout=30; User Instance=True;";
and that error was occurs:
Could not locate entry in sysdatabases for database 'AGMDB'. No entry found with that name. Make sure that the name is entered correctly.
BACKUP DATABASE is terminating abnormally.
how can i solve this error?
Thanks
You need [] around DBFileName, try this:
SqlConnection connect;
connect = new SqlConnection(DAL.AccessLayerClass._connectionStr);
connect.Open();
SqlCommand command;
command = new SqlCommand(#"backup database [" + System.Windows.Forms.Application.StartupPath + "\\Database\\AGMDB.mdf] to disk ='d:\svBackUp1.bak' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
Reference : How to Backup and Restore SQL Express 2005 (AttachDbFilename mode)

Categories