Check if table name exists SQL - c#

How can I check if a table already exists before creating a new one?
Updated Code:
private void checkTable()
{
string tableName = quotenameTxt.Text + "_" + firstTxt.Text + "_" + surenameTxt.Text;
string connStr = #"Data Source=|DataDirectory|\LWADataBase.sdf";
// SqlCeConnection conn = new SqlCeConnection(connStr);
// if (conn.State == ConnectionState.Closed) { conn.Open(); }
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(#"SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tname", conn);
cmd.Parameters.AddWithValue("#tname", tableName);
SqlCeDataReader reader = cmd.ExecuteReader();
if(reader.Read()){
MessageBox.Show("Table exists");}
else{
MessageBox.Show("Table doesn't exist");
createtable();}

Sql Server Compact supports the INFORMATION_SCHEMA views
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(#"SELECT TOP 1 *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tname", conn);
cmd.Parameters.AddWithValue("#tname", tableName)
SqlCeDataReader reader = cmd.ExecuteReader();
if(reader.Read())
Console.WriteLine("Table exists");
else
Console.WriteLine("Table doesn't exist");
}
EDIT
In version 3.5 it seems that the TOP 1 instruction is not accepted. However, given the WHERE clause it should make no difference using it or not so, to make it work just change the query to
SqlCeCommand cmd = new SqlCeCommand(#"SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tname", conn);
SECOND EDIT
Looking at the code that creates the table.
(It is In chat, I suggest to add it to the question for completeness)
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE ['" + tableName + "'] " +
"(Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
The single quotes around the tableName variables becomes part of the name of the table. But the check for table exists doesn't use the quotes. And your code fall through the path that tries to create again the table with the quotes. Just remove the quotes around the name. They are not needed.

You can use the SqlClientConnection to get list of all objects in the db.
private void checkTable()
{
string tableName = quotenameTxt.Text + "-" + firstTxt.Text + "-" + surenameTxt.Text;
string connStr = #"Data Source=|DataDirectory|\LWADataBase.sdf";
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
bool isTableExist = conn.GetSchema("Tables")
.AsEnumerable()
.Any(row => row[2] == tableName);
}
if (!isTableExist)
{
MessageBox.Show("No such data table exists!");
}
else
{
MessageBox.Show("Such data table exists!");
}
}
Source: https://stackoverflow.com/a/3005157/1271037

Related

Updating values from excel to database

I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.

SQLiteDataReader error, near "table": syntax error

I have simple SQLite db table in my C# project
Database Screenshot
Here is the code which I using to retrieve data from DB:
SQLiteConnection dbConnection;
dbConnection = new SQLiteConnection("Data Source=./new.db;");
dbConnection.Open();
if (dbConnection.State == System.Data.ConnectionState.Open)
richTextBox3.Text = "Conn";
string sqlcommand = "SELECT age FROM table WHERE index=1";
SQLiteCommand command = new SQLiteCommand(sqlcommand, dbConnection);
SQLiteDataReader result = command.ExecuteReader();
if(result.HasRows)
{
while (result.Read())
{
richTextBox1.Text = result.GetInt32(0) + " "+ result.GetString(1) + " " + result.GetInt32(2);
}
}
Maybe the while loop is incorrect but my problem is the syntax error near the table.
As #Rohit mentioned table is a keyword in SQLite but if you still want to use it you can change you query as below:
by surrounding your table name by [table]
string sqlcommand = "SELECT age FROM [table] WHERE index=1";
It also works in SQLSERVER
Try adding `` between table because table is reserved word. You can check all reserved words on reserved words
string sqlcommand = "SELECT `age` FROM `table` WHERE `index`='1'";

Check if two tables exist in database

I have database pavadinimas.mdf, which contains two tables: Vehicle and Repairs. I want to check if both tables exist in database. So, far I managed to check if one table exist, but how to check if both exist, if not create them.
Here is my code:
string tblnm = "Vehicle";
SqlConnection conn;
using (conn = new SqlConnection(connection))
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = #"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='" + tblnm + "') SELECT 1 ELSE SELECT 0"; ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
int x = Convert.ToInt32(cmd.ExecuteScalar());
conn.Close();
if (x == 2)
{
MessageBox.Show("Lentelės yra");
}
else
{
MessageBox.Show("Lenteliu nėra.Sukuriama");
}
I also have code which should create table. Here is code:
string table1 = "Repairs";
SqlConnection conn;
conn = new SqlConnection(connection);
conn.Open();
string createString = "CREATE TABLE [dbo].['" + table1 + "'](" + "[VIN] [nvarchar](50)," + "[Taisymas] [nvarchar](50)," + "[Kaina] [decimal](18, 2))";
SqlCommand sqlCmd = new SqlCommand(createString, conn);
sqlCmd.ExecuteNonQuery();
conn.Close();
But this code don't create table in my database. Then I call this method, it is saying that table already exist, but when I check tables in database it's nothing, empty...
Are you looking for something similar to:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='tbl1') AND EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='tbl2') SELECT 1 ELSE SELECT 0
How about using a parameter and looping through the tables?
conn.Open();
var cmd = new System.Data.SqlClient.SqlCommand(
#"SELECT count (*) FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME = #TABLE_NAME",
conn);
cmd.Parameters.Add("#TABLE_NAME", SqlDbType.VarChar);
List<String> tables = new List<string>() { "Vehicles", "Repairs" };
foreach (string tableName in tables)
{
cmd.Parameters[0].Value = tableName;
int x = Convert.ToInt32(cmd.ExecuteScalar());
if (x == 0)
CreateTable(tableName, conn);
}
conn.Close();
-- EDIT --
CreateTable method was added above, and the code would look something like this. Caveat -- this is EXTREMELY brute force, but in the absence of other information, is is one way to accomplish the task, as I best understand your issue.
private void CreateTable(String TableName, System.Data.SqlClient.SqlConnection conn)
{
StringBuilder sql = new StringBuilder(#"create table [");
sql.Append(TableName);
sql.AppendLine(#"] (");
switch (TableName)
{
case "Vehicle":
sql.AppendLine("[VIN] varchar(100),");
sql.AppendLine("[Manufacturer] varchar(100),");
sql.AppendLine("[Model] varchar(100),");
sql.AppendLine("[Year] integer");
break;
case "Repair":
sql.AppendLine("[VIN] varchar(100),");
sql.AppendLine("[Correction] varchar(100),");
sql.AppendLine("[Price] decimal");
break;
}
sql.Append(")");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
sql.ToString, conn);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Created Table " + TableName);
}
catch (Exception ex)
{
MessageBox.Show("Oops, I did it again");
}
}
Wrap it in a for loop
for(int i = 0; i < 2; i++){
if (i = 0)
{
string tblnm = "Vehicle";
}
else
{
string tblnm = "Repairs";
}
SqlConnection conn;
using (conn = new SqlConnection(connection))
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = #"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='" + tblnm + "') SELECT 1 ELSE SELECT 0"; ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
int x = Convert.ToInt32(cmd.ExecuteScalar());
conn.Close();
if (x == 2)
{
MessageBox.Show("Lentelės yra");
}
else
{
MessageBox.Show("Lenteliu nėra.Sukuriama");
}
}

multiple queries on 1 button click

I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();

How list items from table with wildcard in sqlite using c#?

How can I get elements from table using wildcard?
I've made code something like that.
What is wron here? Is it safe if I put this into loop ?
private void Pokaz()
{
String sql = "SELECT [element] FROM [table] LIKE #Word";
SQLiteConnection connection = new SQLiteConnection(#"Data Source=C:\Temp2\dictionary.s3db");
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
DataTable dt = new DataTable();
SQLiteDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
connection.Close();
dataGridView1.DataSource = dt;
}
I changed to String sql = "SELECT [element] FROM [table] where [element] LIKE \'#Word\'";
But now I get empty result.
I tried also this method. Fixed and works. Still above not.
List<string> list = new List<string>();
string connectionString = #"Data Source=C:\Temp2\dictionary.s3db";
string sql = "SELECT [element] FROM [table] where [element] LIKE \'%dog%\' ";
using (var connection = new SQLiteConnection(connectionString))
{
using (var command = new SQLiteCommand(sql, connection))
{
connection.Open();
SQLiteDataReader rd = command.ExecuteReader();
while (rd.Read())
{
list.Add(rd[0].ToString());
}
}
}
Have you tried
String insSQL = "SELECT [element] FROM [table] like #Word"; //% search with prefix and postfix
SQLiteCommand cmd = new SQLiteCommand(insSQL);
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
?

Categories