I need to add column to table, for now I have this code:
public void InsertParameter(string ColumnName)
{
string sql = "ALTER TABLE table_name ADD :value1";
SQLiteCommand cmd = new SQLiteCommand(sql,conn);
cmd.Parameters.AddWithValue("value1", ColumnName);
cmd.ExecuteNonQuery();
}
But this give me syntax error:
near ":value1":syntax error
I really can't figure out what is wrong with this query?
The reason it doesn't work is that the syntax for SQLite's ALTER TABLE statement requires a column-name here instead of an arbitrary string-typed expr. This means you can't use a bind-parameter with it.
(Apparently, the implementation of prepared statements requires the table and column names to be known at “compile” time, so it can't be a variable.)
If you need a C# function that dynamically selects a column name at runtime, you need to dynamically create the SQL statement with a hard-coded column name. (Use double-quoting to prevent SQL injection attacks.)
string sql = "Alter Table table_name ADD "\"" + ColumnName.Replace("\"", "\"\"") + "\"";
Related
I have an insert statement
command.CommandText = " insert into system (ziel, comment, status,art) values (#eort,#comment,#statebox,#Eart) ";
Behind statebox is a Combobox. Every word which can be chosen in the Combobox is created as a tablerow in my database.
the values are created here:
command.Parameters.AddWithValue("#eort",textBo3x.Text);
command.Parameters.AddWithValue("#comment", textBox_Copy1.Text);
command.Parameters.AddWithValue("#statebox", MyComboBox.Text);
command.Parameters.AddWithValue("#Eart", MyComboBox_Copy1.Text);
command.Parameters.AddWithValue("#thetime", thetime_insert.Text);
This works.
But I want to use the #values in the insert Statement like this:
command.CommandText = " insert into els (ziel, #statebox,comment,status,Eart) values (#eort,#thetime,#comment,#statebox,#Eart) ";
This gives me an mysql error.
It seems that the #values have '' at the words.
How can i delete this?
Your INSERT statement as pointed below is wrong. You can't simply plug-in a dynamic column in your insert statement which doesn't exists in your table schema
insert into system (ziel, #statebox,comment,status,Eart)
This can only be done in case of SELECT statement and doing below is perfectly alright
select ziel, #statebox,comment,status,Eart from `system`
Well, if you have your column name in variable then build your query string like
string query = string.Format("insert into els (ziel, {0},comment,status,Eart) values ", column_name_variable);
You cannot use a parameter to reference a field name. However, if you provide your user with a predetermined list of fields between he/she can choose then you can safely use a form of string concatenation to insert the field to update/insert into.
This means that you need to have a combobox without any editing capability but just a selection of the possible fields.
In your case, it seems that this combobox could be the one named MyComboBox
Thus
command.CommandText = #"insert into els
(ziel, " + MyComboBox.SelectedItem.ToString() +
#",comment,status,Eart) values
(#eort,#thetime,#comment,#statebox,#Eart)";
Said that consider to remove the use of AddWithValue. This shortcuts has big drawbacks, in particular when you pass a string variable (Text) and expects it to correctly translate your text in a datetime value.
Use the Add method instead converting and checking your inputs and specifying the correct datetype for the parameter.
DateTime dt;
if(!DateTime.TryParse(thetime_insert.Text, out dt);
// Message, not a valid date....
else
command.Parameters.Add("#thetime", MySqlDbType.Date).Value = dt;
I check my SQL database to see if a column exists if not create, but I wanted to insert a string in that column, but only if the column didn´t exist.
Otherwise I handle that information in my C# code.
So far I have this code :
string query = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tabela' AND COLUMN_NAME = 'coluna') ALTER TABLE tabela ADD coluna varchar(50)" ;
SqlCommand command = new SqlCommand(query, con);
command.ExecuteNonQuery();
How should I do ?
Change your query to execute a block after the IF (psuedocode):
IF NOT EXISTS(...)
BEGIN
ALTER TABLE MyTable ...;
INSERT INTO MyTable ...;
END
Be sure to put semicolons at the end of the ALTER and INSERT commands, since you are sending these in a single command from an application, so SQL Server will see them as being all on one line.
You can write a trigger for each SELECT from the database object. In that you can first check if the column exists, and then you can do the needful. This you can achieve entirely by using SQL triggres (or even stored procedures
), C# has nothing to do with it :)
For more details on triggers, you can check this out
I have the following code:
string strTruncateTable = "TRUNCATE TABLE #TableNameTruncate";
SqlCommand truncateTable = new SqlCommand(strTruncateTable, myConnection);
truncateTable.Parameters.AddWithValue("TableNameTruncate", tbTableName.Text);
truncateTable.ExecuteNonQuery();
Whenever I run the application, I get the following error:
Incorrect syntax near '#TableNameTruncate'
How can I fix the issue?
How can I fix the issue?
By specifying the table name as part of the SQL. Table and column names can't be parameterized in most database SQL dialects, including SQL Server.
You should either perform very stringent validation on the table name before putting it into the SQL, or have a whitelisted set of valid table names, in order to avoid SQL injection attacks in the normal way.
You can only parameterized your values, not your column names or table names no matter you use DML statements or DDL statements.
And by the way, parameters are supported for Data manipulation language operations not Data Manipulation language operations.
Data manipulation language =
SELECT ... FROM ... WHERE ...
INSERT INTO ... VALUES ...
UPDATE ... SET ... WHERE ...
DELETE FROM ... WHERE ...
TRUNCATE TABLE is a Data Definition Language statement. That's why you can't use TRUNCATE TABLE with parameters even only if you try to parameter a value. You need to specify it as a part of SQL query.
You might need to take a look at the term called Dynamic SQL
As mentioned by Jon Skeet, table name cannot be parametrized for truncate operation.
To fix this issue, fully qualified query needed to be written.
So you can put a conditional check by the parameter value #TableNameTruncate and using if or switch case statement create fully qualified query then execute it.
or simply
string strTruncateTable = "TRUNCATE TABLE " + TableNameTruncate.Value;
SqlCommand truncateTable = new SqlCommand(strTruncateTable, myConnection);
truncateTable.Parameters.AddWithValue("TableNameTruncate", tbTableName.Text);
truncateTable.ExecuteNonQuery();
I Try to insert to MySQL database in C#, but what i got is this error
"You have an error in your SQL syntax; check the manual that
corresponds to your Mysql server version for the right syntax to use
near "insert (NoNota, Nama, Tanggal, Tipe, Keterangan) VALUES ('1111',
'Kickass', '201" at line 1
i think the problem is the DateTime, in my database datatype i set it to DATETIME, Here is my code
string sqlQuery;
sqlQuery = "INSERT INTO insert (id, Name, Date, Type, Notes) VALUES ('1111', 'Kickass', '2013-09-09', 'Cash', 'Nothing')";
if (this.OpenConnection() == true)
{
cmd = new MySqlCommand(sqlQuery, connect);
cmd.ExecuteNonQuery();
CloseConnection();
MessageBox.Show("Operation INSERT is SUCCESS!!");
}
What's wrong with it? i try excute my SQL Queries it work very FINE in MySQL Workbench, it automatically convert the DateTime and insert it into the table. Any clue?
insert is a reserved word (INSERT INTO insert). Rename the table or escape with backticks. I'd highly recommend renaming.
You need to escape reserved words in MySQL like INSERT with backticks
INSERT INTO `insert` (id, Name, ...
^------^---------------------here
But it would be way better to rename your table. insert does not say anything about your data. Try to think of its content. When you have hundreds of tables in a database you need to name every one very carefully to keep track what it contains.
When you name your column, name it after the single word that finishes this sentance:
The data of my table holds ...
I have an SQL table called tbl, im trying to add the columns A, B and C to it.
When i execute the command :
String addcolumns = "ALTER TABLE SqlCreatedTbl ADD A char(50) ;";
......
cmd = new SqlCommand(addcolumns, conn);
conn.Open();
cmd.ExecuteNonQuery();
The column is added !
However, when i try to add multiple columns, it does NOT work, it gives me an error..
the command im writting for adding multiple columns is the following:
addcolumns = "ALTER TABLE SqlCreatedTbl ADD ( A char(50), B char(50), C char(50) );";
the debugger highlights the line : cmd.ExecuteNonQuery(); and throws the following exception:
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '('.
Get rid of the parentheses you've added in the ADD clause. You don't have them in the single column version, and you don't need them with multiple columns either. Specify ADD once and then just comma-separate your list
If you're interacting with an SQL Server database (using T-SQL), you must not place parentheses around your list of column definitions even when adding multiple columns:
ALTER TABLE SqlCreatedTbl ADD A char(50), B char(50), C char(50);