I want my app to connect to server and create database on whatever pc it runs. I have code, but it works only on my computer and not others, when i run it on other computers it won't connect to that computers server and won't create database
This is my code, I have splash screen form and I want, when app runs, to check if database exists on that pc and if don't to create it. What my problem is, is that my code doesn't catch server name and just shows message "Bad server name"
public partial class Splash : Form
{
public Splash()
{
InitializeComponent();
Properties.Settings.Default.Server = "(local)";
timer.Enabled = true;
}
private void CheckDatabase()
{
try
{
using (SqlConnection conn = Helper.ConnectionToServer())
{
if (Properties.Settings.Default.Server != string.Empty)
{
using (SqlCommand cmd = new SqlCommand(
"IF EXISTS (SELECT name FROM sys.databases WHERE name = 'MyDb') SELECT 1 ELSE SELECT 0",
conn))
{
conn.Open();
int value = (int)cmd.ExecuteScalar();
conn.Close();
if (value != 1)
{
MessageBox.Show("Database doesn't exist");
timer.Enabled = false;
CreateDatabase();
}
}
}
else
{
timer.Enabled = true;
}
}
}
catch
{
MessageBox.Show("Bad server name");
}
}
private void CreateDatabase()
{
string serverStr = "CREATE DATABASE [MyDb]";
string databaseStr = @"
CREATE TABLE [dbo].[Worker] (
[FirstName] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[LastName] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Password] ASC)
);
CREATE TABLE [dbo].[Article] (
[ItemName] NVARCHAR (50) NOT NULL,
[Barcode] NVARCHAR (50) NOT NULL,
[Price] MONEY NOT NULL,
CONSTRAINT [PK_Article] PRIMARY KEY CLUSTERED ([Barcode] ASC)
);";
using (SqlConnection conn = Helper.ConnectionToServer())
{
try
{
using (SqlCommand comm = new SqlCommand(serverStr, conn))
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
catch
{
MessageBox.Show("Bad server name");
}
}
using (SqlConnection conn = Helper.ConnectionToDatabase())
{
using (SqlCommand comm = new SqlCommand(databaseStr, conn))
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
timer.Enabled = true;
}
}
}
I have a helper class also that I use whenever I use sql commands
class Helper
{
public static SqlConnection ConnectionToDatabase()
{
string con = string.Format(@"Data Source=DESKTOP-RFJ38NM;Initial Catalog=MyDb;Integrated Security=True", Properties.Settings.Default.Server);
return new SqlConnection(con);
}
public static SqlConnection ConnectionToServer()
{
string con = string.Format(@"Data Source=DESKTOP-RFJ38NM;Integrated Security=True", Properties.Settings.Default.Server);
return new SqlConnection(con);
}
}