I am trying to create a SQL Server table programmatically. Here is the code.
using (SqlConnection con = new SqlConnection(conStr))
{
try
{
/
For managing DataBase Objects in SQL Server i would suggest using Server Management Objects
First, check whether the table exists or not. Accordingly, create table if doesn't exist.
var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";
using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();
using System;
using System.Data;
using System.Data.SqlClient;
namespace SqlCommend
{
class sqlcreateapp
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
conn.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Table Created Successfully...");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
You haven't mentioned the Initial catalog
name in the connection string. Give your database name as Initial Catalog
name.
<add name ="AutoRepairSqlProvider" connectionString=
"Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
Integrated Security=True;User Instance=True"/>
Try this
Check if table have there , and drop the table , then create
using (SqlCommand command = new SqlCommand("IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#Customer%')
DROP TABLE #Customer CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
try
{
cn.Open();
SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
cmd.ExecuteNonQuery();
lblAlert.Text = "SucessFully Connected";
cn.Close();
}
catch (Exception eq)
{
lblAlert.Text = eq.ToString();
}
}