I am executing a dynamically generated MySQL query using C# code. An exception gets thrown:
CREATE TABLE dump ("#employee_OID" VARCHAR(50));
"{"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\"#employee_OID\" VARCHAR(50))' at line 1"}"
I cannot skip the '#' symbol from the Column Name.
Manually, using MySQL Workbench, I can get it executed after executing the following query.
SET sql_mode='ANSI_QUOTES';
Following is the code I am able to produce:
MySqlConnection conn = null;
MySqlCommand cmd = null;
string mySQLConnectionString = ConfigurationManager.AppSettings["MySQLAutomationServerConnectionString"];
//Dynamically getting generated using some other code
string sqlQueryString = "CREATE TABLE dump ("#employee_OID" VARCHAR(50));";
try
{
conn = new MySqlConnection(mySQLConnectionString);
conn.Open();
cmd = new MySqlCommand(sqlQueryString, conn);
executionResultStatus = cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
Console.WriteLine("MySQL Exception: " + ex.Message.ToString());
}
I have tried to execute the "SET sql_mode='ANSI_QUOTES';" query before this gets executed using the code right before executing this code, its not working. What shall I do?
Change your command to
string sqlQueryString = "CREATE TABLE dump (`#employee_OID` VARCHAR(50));";
Notice how there are two backticks before and after the problematic name (ALT+096)
This will allow your engine to ignore the character # used to identify parameters
Related
I am trying to get the length of a specific column in a table which table is from a database called Users in a visual studio C# form application. First of all i know it has to do with the column.length command but since those examples i have a searched i got lost.
Can someone tell me a simple way to get this happen? For more specific information i have a table called user_info and it contains a column which name is searches. I want to get the length of searches into a single variable
Here is the C# code that you need to pull the column size from the database. Make sure you update the connString variable to contain your own SQL server connection string.
Example: "Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)"
Int32 columnSize = 0;
string sql = "SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'user_info' AND COLUMN_NAME = 'searches'";
string connString = "Your Sql Server Connection String";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
columnSize = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I'm trying to add a new column to a table in my CE database using C# code.
This SQL works in SSMS to add to a standard SQL database table:
IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N'sent' AND Object_ID = Object_ID(N'QAReports')) BEGIN
ALTER TABLE QAReports ADD [Sent] bit NULL;
END
But when I try to run the same sql in C# I get an error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = IF ]
My code that I'm using to execute the SQL above is:
bool retVal = true;
try
{
using (var connection = new SqlCeConnection(ConnString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
connection.Close();
}
}
catch (Exception ex)
{
retVal = false;
}
return retVal;
Is there a way to do what I want to do.
Is there a better way. I'm trying to upgrade a database on an end-users installation if they need it. I check a value in the database that tells me what app version was last used on it. Then I want to run the SQL to add the required fields and then update the value in the database for the app version.
I'm trying to execute a very simple SQL statement on an Access database through C#.
The statement is something like this:
select M_PASSWORD from TB_USERS where M_USERNAME = 'myuser'
and this is the C# code I'm using to execute the SQL statement:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sources.global_variables.db_source;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT #1 from #2 WHERE #3='#4'", connection);
command.Parameters.AddWithValue("#1", db_column);
command.Parameters.AddWithValue("#2", db_table);
command.Parameters.AddWithValue("#3", db_where_column);
command.Parameters.AddWithValue("#4", db_where_value);
reader = command.ExecuteReader();
//rest of code
Once I get to the line reader = command.ExecuteReader();, the reader fails the execution of the query giving me the following error message: OleDBException was unhandled: Syntax error in query (Incomplete query clause).
I've debugged the code to see if I could see any wrong assignment in the parameters values, but they look fine.
Moreover, executing the exact same query on the Query Analyzer of the Database, I retrieve the value I want.
Could anyone give a tip to spot the problem and understand where I'm wrong?
I think you cant pick column names as parameter such that. It might be the problem.
Use if statement or other conditional statements for parameter and move your query to inside of your conditional statement.
I don't believe that parameters can be used in the fashion you posted. Parameters are used for filling in values (ie, placing a DateTime value into an update statement as the value of a DateTime column to be updated in a table).
Try changing your code such that the column names and table names are provided in text or are filled in as a string. You can build the query string up if you want to fill in different column names, different table names, and different column names in your where clause. So instead of what you posted, try something more like this:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sources.global_variables.db_source;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
string strQuery = "SELECT " + constStringColumnName1 + " FROM " + theTableNamePassedInAsString + " WHERE " + strWhereClauseBuiltEarlierInThisFunction + " = '#1'";
OleDbCommand command = new OleDbCommand( strQuery , connection);
command.Parameters.AddWithValue("#1", db_where_value);
reader = command.ExecuteReader();
//rest of code
}
Of course, you could format the string and plug in your changing selection column name, your table name, and your where clause. Build your select/command string, then use Parameters to fill in the actual value is the normal usage.
Try remove the ' on where parameter and use ? insted of # like that
OleDbCommand command = new OleDbCommand("SELECT ? from ? WHERE ?=?", connection);
command.Parameters.AddWithValue("column", db_column);
command.Parameters.AddWithValue("table", db_table);
command.Parameters.AddWithValue("where_column", db_where_column);
command.Parameters.AddWithValue("where_value", db_where_value);
I dont know if you can use parameters on column name. If it won´t running try to execute the query without parameters using concat and only use parameters on where value
Why do I get an exception when trying to truncate a MySQL table (using MySQL Connector/Net)? I am trying to give the table name with a parameter.
This is the code I'm executing:
var connectionString = "Server="+_server+";Uid="+_user+";Pwd="+_password+";Database="+_database+";";
try
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
const string sql = "TRUNCATE TABLE #tablename"; // also tried with TRUNCATE #tablename
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#tablename", "test");
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
And this is the execption:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQ L syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ''test'' at line 1
When I try a select query, for example, then I don't have any problems. This runs fine and returns correct data:
conn.Open();
const string sql = "SELECT body FROM test WHERE id=#pid";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#pid", 1);
cmd.ExecuteScalar();
conn.Close();
Parameters are used for query values, not object names like tables.
So this will not work for sure.
You need to set the table name in the command string by using string concatenation. You can avoid sql injection attacks by manually checking for weird characters in the table name (spaces, dashes, semicolons, etc..)
I've been playing around with this for a while now, and i can't seem to get it to work either. I can't find any documentation online, so i'm starting to think you may not be able to truncate with a parameter like you've tried.
However, is there really a need to prevent SQL injection on this command? Does the user enter the name of the table they want to truncate, and if so, they're just going to truncate a table which...is essentially what the command does anyway?
i am using this code below to allow me to go into my sql sever and get the data out and input the data into a datatable... but there is no data being added to the table and the table in the database has information in the table.
// SQL Server Connection Strings
sqlConnectionString = "Data Source=.;Initial Catalog= " + databaseName + " ;Integrated Security=true";
queryString = "select * from " + sqlTableName;
using (var connection = new SqlConnection(sqlConnectionString))
using (var adapter = new SqlDataAdapter(queryString, connection))
{
sqlDataTable.Clear();
adapter.Fill(sqlDataTable);
}
return sqlDataTable;
There could be four possible errors in your code
1) Try adding schema name (for example "dbo")
queryString = string.Format("select * from [dbo].['{0}']",sqlTableName);
2) Unhandled Exception
From MSDN DataTable.Clear()
All rows in all tables are removed. An exception is generated if the table has any enforced child relations that would cause child rows to be orphaned.
I think at the point of sqlDataTable.Clear() your code is getting error (or somewhere else) which you are not handling by try catch block. so the datatable is empty.
3) database Table is empty
4) Doesn't matter but try adding connection.Open().
I cant say anything more until you show the complete code related to this function and how you are assigning this function(or method) to your original DataTable
Try to begin a transaction and commit it after you have added the data. I don't know much about C#, but I see a BeginTransaction() method on the SqlConnection object.