I'm currently developing a small WPF application.
I generate sql script file that contains commands to create database and tables, views, procedures and so on.
But where in my wpf code I must put this script or how to read the sql script file during first run and create database and tables? Other if the client choose a diferente folder and directory to install the application how to get a path of sql script file? I use Visual Studio Installer.
void excuteScript()
{
String connString = #"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=True";
String cmdText = "select * from master.dbo.sysdatabases where name= 'Teste'";
Boolean bRet;
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection);
try
{
sqlConnection.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
bRet = reader.HasRows;
sqlConnection.Close();
}
catch (Exception e)
{
bRet = false;
sqlConnection.Close();
MessageBox.Show(e.Message);
}
if (bRet == true)
{
}
else
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=master;Integrated Security=True";
var file = new FileInfo(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"teste.sql"));
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
Related
I have an application that uses SQL Server and I am working on a setup that should generate the Database on the Client machine from a script.
As a prerequisite for installation I have selected SQL Server Express 2012 and the .Net Framework.
My question is, will SQL Server Express 2012 be enough to make accessing the database possible on the Client machine?
Also, will my Code for generating the Database from the script run on another PC, specifically the "Data Source=.\BeneSQL" worries me, since that is "unique" to my PC, or will the script generate that part aswell?
private void Form1_Load(object sender, EventArgs e)
{
if (!CheckDatabaseExist())
{
GenerateDatabase();
}
}
private bool CheckDatabaseExist()
{
SqlConnection sqlConnection = new SqlConnection(#"Data Source=.\BeneSQL;Initial Catalog=TryingDB;Integrated Security=True");
try
{
sqlConnection.Open();
return true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return false;
}
}
private void GenerateDatabase()
{
List<string> cmds = new List<string>();
if (File.Exists(Application.StartupPath + "\\Skript.sql"))
{
TextReader tr = new StreamReader(Application.StartupPath + "\\Skript.sql");
string line = "";
string cmd = "";
while ((line = tr.ReadLine()) != null)
{
if (line.Trim().ToUpper() == "GO")
{
cmds.Add(cmd);
cmd = "";
}
else
{
cmd += line + "\r\n";
}
}
if (cmd.Length > 0)
{
cmds.Add(cmd);
cmd = "";
}
tr.Close();
}
if (cmds.Count > 0)
{
SqlCommand command = new SqlCommand();
command.Connection = new SqlConnection(#"Data Source=.\BeneSQL;Initial Catalog=MASTER;Integrated Security=True");
command.CommandType = System.Data.CommandType.Text;
command.Connection.Open();
for(int i=0; i<cmds.Count; i++)
{
command.CommandText = cmds[i];
command.ExecuteNonQuery();
}
}
}
It depends on what instance name will be used for the SQL Server 2012 installation.
If SQL Server is installed on a default instance (.) without name, your code will not work, because it will not be able to connect to the instance .\BeneSQL , because it will not exist.
Otherwise, if SQL Server is installed on an instance named BeneSQL , then your code should work, because it will find the instance.
I can't see that working for the reasons you suspect.
Try
command.Connection = new SqlConnection(#"Data Source=localhost;Initial Catalog=MASTER;Integrated Security=True");
Maybe it's repetitive but I googled and didn't find my answer.
I developed a program by .net that has a local database (Express) that works excellently on my computer, but when I create a setup and installation, it can't insert or update and so on for example in Delete() method I have
try
{
}
catch
{
}
in the exefile always goes to the catch{} section and I don't know why :((
This is my connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30
This is one of my methods for example:
private Boolean Delete(int id)
{
//String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(Connection);
String sqll = "Delete FROM TblBank WHERE Id =#id ";
try
{
sql.Open();
SqlCommand cmd = new SqlCommand(sqll, sql);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
MessageBoxEx.Show("have some problem", "wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
and Necessary say i put my .mdf and .ldf file into my setup folder and make setup by Visual Studio Installer
Try this
private bool Delete(int id)
{
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(connString);
String sql = "Delete FROM TblBank WHERE Id =#id ";
try
{
sqlConn.Open();
SqlCommand cmd = new SqlCommand(sql, sqlConn);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.Message, "wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
So that you can see what the error is. At the moment you are just saying something went wrong when ex contains everything you will need to debug the problem.
Hope this helps.
(There are a few things to refactor too, such as wrapping your connection in a using statement.)
The cause of your problem is very simple. There can be two situations in your case. They are as follows:
The computer you are trying to run the application doesn't have the proper version of the sql server.
Solution: In this case, you have to find out in which sql server version you have created your database. Then you have to include that version of sql server into the setup.exe package. So that when the setup.exe executes the proper sql server also setups with your application.
The computer you are trying to setup the application has proper sql version but still you are getting the error.
Solution: First delete your existing database and create new database from solution explorer.Then use this particular connection string given below
SqlConnection conn = new
SqlConnection (global::ProjectName.Properties.Settings.Default.ProjectConnectionString);
ProjectConnectionString can be found in App.config file after you connect your database to your solution.
Hope this helps. Feel free to ask in the comment if you need to.
#Parnian It should required to install local db in your system.
1.when you click server object explorer and then when you click on Localdb server you will get proper connection string from properties .
enter code here static void Main(string[] args)
{
TestConncetion testConncetion = new TestConncetion(Delete);//here I used delegate
WriteLine($"My connection string is working Fine ,result is {testConncetion(1)}");
}
private static bool Delete(int id)
{
string Connection = #"Data Source=(localdb)\ProjectsV13;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(Connection);
string sqll = "Delete FROM TblBank WHERE Id =#id ";
try
{
sql.Open();
SqlCommand cmd = new SqlCommand(sqll, sql);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
WriteLine("have some problem", "wrong", ex.Message);
return false;
}
}
My issue is that I keep getting an error on console that says
Invalid Object Name 'dbo.Products'
I am using Visual C# 2008 Express Edition and SQL Server 2008 Express.
I have had some issue with preparing/installing the Northwind sample database, so I'm unsure if that has any weight on the issue though. Our teacher gave a test program which is the program I am receiving this error.
static void Main()
{
string connectionString =
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server 2000 Sample Databases\\PUBS.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
string queryString =
"SELECT ProductID, UnitPrice, ProductName FROM dbo.Products "
+ "WHERE UnitPrice > #pricePoint "
+ "ORDER BY UnitPrice DESC;";
int paramValue = 5;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#pricePoint", paramValue);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
Your database is not Northwinds but Pubs.
Check the Connection String
string connectionString =
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server 2000 Sample Databases\\PUBS.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
Specifically on AttachDBFileName:
AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server 2000 Sample Databases\\PUBS.MDF
Try to change it to Northwinds (given it is in the same folder as Pubs), like:
AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server 2000 Sample Databases\\Northwind.MDF
Update:
Try to use SqlCeConnection instead of Sqlconnection because it looks like you are using compact or SDF:
using (SqlConnection connection =
new SqlConnection(connectionString))
To:
using (SqlCeConnection connection =
new SqlCeConnection(connectionString))
POSSIBLE DUPLICATE OF :
How to create SQL Server 2008 database full backup programmatically in desired folder
I have a database on my computer (SQL Server 2008 Express).
I need any sample code in C# that I can use to backup the database to a file using Visual Studio 2010.
Thanks..
i'll using this code to connect Database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Just execute SQL Server command
BACKUP DATABASE database_name TO DISK='d:\path\to\backup\file\on\the\server.bak'
from your program
EDIT
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;
Integrated Security=True; User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
SqlCommand command;
command = new SqlCommand(#"backup database SMS_DB.mdf to disk ='" + path + "\\" + name, con);
command.ExecuteNonQuery();
MessageBox.Show("Backup Created.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Try this peice of code.
Im using flowing code to connect database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
can i use your SQL Command to set backup using upon type connection
This what I did and it Worked!
private void BackupButtonClick(object sender, RoutedEventArgs e)
{
// FILE NAME WITH DATE DISTICNTION
string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
try
{
// YOUR SEREVER OR MACHINE NAME
Server dbServer = new Server (new ServerConnection("DESKTOP"));
Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
{
Action = BackupActionType.Database,
Database = "School"
};
dbBackup.Devices.AddDevice(#backupDirectory() +"\\"+ fileName, DeviceType.File);
dbBackup.Initialize = true;
dbBackup.SqlBackupAsync(dbServer);
MessageBox.Show("Backup", "Backup Completed!");
}
catch(Exception err)
{
System.Windows.MessageBox.Show(err.ToString());
}
}
// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
return dialog.SelectedPath;
}
}
I'm having problem with the following C# code to perform a backup, particularly in the connection string.
The code is as follows:
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
//Query per backup
string queryBK = "BACKUP DATABASE db TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
This code works on the development PC, but if I install my application on another PC it throws this error:
The database does not exist. Verify that the name has been entered
correctly. INTERRUPTION ANOMALOUS BACKUP DATABASE.
I would stress that this string works well with the operations INSERT, DELETE, UPDATE
on both my PC and on the PC test.
If I replace the connection string with:
string strconn = #"Data Source=.\SQLEXPRESS; Database = db;Trusted_Connection =True";
The string works on my dev machine but not on the test machine. It throws the following error:
Can not open database requested by the login. Login failed. Login
failed for user Pina-PC \ Pina
Dear fellow you can use your code in this way.
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
// First get the db name
conn.Open();
string dbname;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
dbname = cmd.Connection.Database.ToString();
//Query per backup
string queryBK = "BACKUP DATABASE " + dbname + " TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
this routine will work in your case.