SQLiteDataReader error, near "table": syntax error - c#

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'";

Related

How to prevent adding same data to SQL from C# program

This is our code to prevent the same data from being added into SQL from our C# program but only the first same data will not be added in. The remaining ones adds the same data into SQL despite our prevention in our C# program. Can somebody help us troubleshoot?
in order not to duplicate data in database usually you set some constraints to your database. By having a unique field in database you can prevent multiple addition to your db.
Currently you are also fetching data from db to check if it exist already and that creates extra cost, just manipulate the design of db so that it won't accept the same column input twice
Count the value of data that is inserted
string constr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection con = new SqlConnection(constr);
string sql1 = "SELECT COUNT (client_id) FROM client WHERE client_id = '" + txtid.Text + "' ";
SqlCommand cmd = new SqlCommand(sql1, con);
con.Open();
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp >0)
{
//show error message
}
You could check for the record you want to add, and if it doesn't exists, then add it to the table:
SqlConnection _cnt = new SqlConnection();
_cnt.ConnectionString = "Your Connection String";
SqlCommand _cmd = new SqlCommand();
_cmd.Connection = _cnt;
_cmd.CommandType = System.Data.CommandType.Text;
_cmd.CommandText = "SELECT id FROM myTable where Category=#Name";
_cmd.Parameters.Add("#Name", string);
_cmd.Parameters["#Name"].Value = newCatTitle;
_cnt.Open();
var idTemp = _cmd.ExecuteScalar();
_cmd.Dispose();
_cnt.Close();
_cnt.Dispose();
if (idTemp == null)
{
//Insert into table
}
else
{
//Message it already exists
}

Check if table name exists SQL

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

How to dynamically add lables for every name in MYSQL database?

I have a MYSQL database and I am trying to get the first name and last name of every student I put in the database and dynamically show them as a label in my WPF form, here is what I got so far
string connstr = "Server=localhost; Database=login; UID=root; Pwd=password";
MySqlConnection connc = new MySqlConnection(connstr);
MySqlCommand command;
connc.Open();
// Label[] labels = new Label[n];
try
{
command = connc.CreateCommand();
command.CommandText = "SELECT First_name, Last_name FROM Students";
command.ExecuteReader();
MessageBox.Show("S");
}
catch (Exception ex)
{
MessageBox.Show("something went wrong: " + ex.ToString());
}
finally
{
connc.Close();
}
So how could I add all my entry's in the database to a label?
ExecuteNonQuery method just executes your query. You can't get your values with it.
You need to use ExecuteReader at least to get your values. You can read your column values in a while statement with MySqlDataReader.Read() method. This method reads your query row by row.
Also use using statement to dispose your MySqlConnection, MySqlCommand and MySqlDataReader.
using(MySqlConnection connc = new MySqlConnection(connstr))
using(MySqlCommand command = new MySqlCommand("SELECT First_name, Last_name FROM Students", connc))
{
using(MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// reader[0] gets you first column which is First_name
// reader[1] gets you second column which is Last_name
// Do your label assingments..
}
}
}
First , ExecuteNonQuery() method is used for DML statements INSERT ,UPDATE , DELETE .
Use ExecuteReader() method.
command = connc.CreateCommand();
command.CommandText = "SELECT First_name, Last_name FROM Students";
SqlDataReader dr = command.ExecuteReader();
string result=string.Empty;
while(dr.Read())
{
result += dr["First_name"].ToString() + " " + dr["Last_name"].ToString();
}
lableId.Content=result;

SQL Query Problems with Tables

public void SPROC_LoadGroups()
{
//This gets the table name.
string tablename = cboNetChannel.SelectedItem.ToString();
SqlConnection sqlConnectionCmdString = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Rick\Documents\Visual Studio 2010\Projects\Server\database\ClientRegit.mdf;Integrated Security=True;User Instance=True");
//This is the table name and Query that identifies with the selected table
string Command = "SELECT Client_Groups" + "FROM" + tablename;
SqlCommand sqlCommand = new SqlCommand(Command, sqlConnectionCmdString);
SqlDataAdapter objDA = new SqlDataAdapter(sqlCommand);
DataSet dsGroups = new DataSet();
objDA.Fill(dsGroups, "dtGroup");
cboExistingG.DataSource = dsGroups.Tables["dtGroup"];
cboExistingG.DisplayMember = "Client_Groups";
//cboExistingG.ValueMember = "ID";
}
Error I am getting is this {"Incorrect syntax near '-'."}
I got a situation is it possible to query as table with a name similar to a GUID value
my table name is 43d5377-0dcd-40e6-b95c-8ee980b1e248
I am generating groups that are identified with a Networking Data table that is named 43d5377-0dcd-40e6-b95c-8ee980b1e248 The table name is allowed and SQL does not prohibit such table names.
This is my code I am getting an error, I am table mapping with this by creating a Query that allows me to identify the query with the selected table value.
If your table name is similar as a GUID add [] block
something like:
string Command = "SELECT Client_Groups FROM [" + tablename+ "]";
Best Regards
You were missing a space between the concatination of these two strings:
"SELECT Client_Groups" + "FROM"
change to
"SELECT Client_Groups " + "FROM "
SqlCommand cmd;
cmd = new SqlCommand("SELECT client_Groups FROM Table name where name='" + txtbox. Text + "' , lastname='" + txtbox. Text + "'", con);

"Data type mismatch in criteria expression" when trying to delete row from database

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

Categories