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");
Related
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;
}
}
I tried to detach my local database .mdf copy it in another folder and attach the new file at launch and copy to the older folder when closing.
It seems to works at launch but i have an error when the form closing :
The process cannot access the file 'C:\ProgramData\MyData\db1.mdf' because it is being used by another process.
That's my code :
public Form()
{
InitializeComponent();
DetachDatabase();
CopyDb();
AttachDatabase();
AppDomain.CurrentDomain.SetData("DataDirectory", Data.MyNewFolder);
}
public static bool DetachDatabase()
{
try
{
string connectionString = String.Format(#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True");
using (var cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = String.Format("exec sp_detach_db '{0}'", "db1");
cmd.ExecuteNonQuery();
cmd.CommandText = String.Format("exec sp_detach_db '{0}'", "db2");
cmd.ExecuteNonQuery();
return true;
}
}
catch
{
return false;
}
}
public static bool AttachDatabase()
{
try
{
string connectionString = String.Format(#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True");
using (var cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = String.Format("exec sys.sp_attach_db db1, 'db1.mdf'");
cmd.CommandText = String.Format("exec sys.sp_attach_db db2, 'db2.mdf'");
cmd.ExecuteNonQuery();
return true;
}
}
catch
{
return false;
}
}
private void Frm_FormClosing(object sender, FormClosingEventArgs e)
{
LocalDB.DetachDatabase();
CopyDb();
LocalDB.AttachDatabase();
}
what is the good way for do it ?
Thanks
You need to switch to master and put the target database offline
WARNING: Use at your own risk (e.g. can you use WITH ROLLBACK IMMEDIATE?)
var commandText = string.Format(#"
USE MASTER;
ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE;
EXEC sp_detach_db '{0}', 'true';", "db1");
The second parameter to sp_detach_db just avoids statistics update (would be faster)
You can now safely move the mdf and ldf files from their original location
Assuming your database is already offline and you have moved your db1.mdf file into D:\Whatever, I think you can do this ( I didn't test it, beware )
var commandText = string.Format(#"
USE MASTER;
ALTER DATABASE {0}
MODIFY FILE (
NAME = '{0}',
FILENAME = 'D:\Wherever\{0}.mdf');
ALTER DATABASE {0} SET ONLINE;", "db1");
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);
}
}
I have a standart local Oracle DB to which i can connect with my sqldeveloper
using connection with :
username = system
password = orcl
hostname = localhost
port = 1521
SID = ORCL
but when i'm trying to do this in the code
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "HR_ORCL";
builder.UserID = "system";
builder.Password = "orcl";
string connectionString = "Server=(local);Database=HR_ORCL;User ID=system;Password=orcl";
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = builder.ConnectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
}
}
catch(Exception error)
{
System.Console.WriteLine(error.Message);
}
I'm getting an error
"provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL server"
What am i doing wrong ?
As correctly said by Stefan you need to download and install ODP from this site
Once the installation is done you need to add a reference of the assembly Oracle.DataAccess.dll.
And then you can use it like this:
using System;
using Oracle.DataAccess.Client;
class MyClass
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "yourconnectionstring";
con.Open();
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
//some code
}
}
iam writing a c# windows application to store some data into a sql server database , but when i make an attempt to attach my mdf database file to visual studio the above error appears here's the code below , what can i do ? Thanks.
public partial class Add_Client : Form
{
SqlConnection clientConnection;
string connString;
SqlCommand insertCommand;
public Add_Client()
{
InitializeComponent();
connString = "Data Source=ESLAM\\MSSQLSERVER;Initial Catalog=Clients; Integrated security=true ";
clientConnection = new SqlConnection();
clientConnection.ConnectionString = connString;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand insertCommand = new SqlCommand();
insertCommand.Connection = clientConnection;
insertCommand.CommandText = "INSERT INTO Client_Info values(#Client_Name,#Autorization_No,#Issue_Type,#Status)";
insertCommand.Parameters.Add("#Client_Name", SqlDbType.NVarChar, 60).Value = txt_Name.Text;
insertCommand.Parameters.Add("#Autorization_No", SqlDbType.Int, 60).Value = txt_Auth.Text.ToString();
insertCommand.Parameters.Add("#Issue_Type", SqlDbType.Text, 200).Value = txt_Iss.Text;
insertCommand.Parameters.Add("#Status", SqlDbType.Text, 200).Value = txt_Iss.Text;
//insertCommand.Parameters.Add("#Date To Memorize", SqlDbType.Date, 15).Value=Ca_Mem.se;
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (clientConnection != null)
{
clientConnection.Close();
}
}
}
}
Your connection string is just trying to connect to a running instance (.\INSTANCE2) of sql server with the DB (Client) already attached. The error is saying there is no sql server instance running with that name on the local machine. Nothing there will attach anything to anywhere.
Here are instructions on how to get an mdf file attached in sql server express. If you run sqlcmd as a postbuild task in visual studio and run the a modified version of the script for your db and it will start sqlserver and attach your database after you build.