I have a problem in button1 click event of inserting data into a table which table name be determined by whatever text is in textbox1
Should mean something like that:
tablename = textbox1.text;
sql = "INSERT INTO tablename ([itemserial], [itemname], [itemcount],[itemimage]) VALUES (#itemserial, #itemname, #itemcount, #itemimage)";
Having a textbox containing the name of your table is challenging because you should add extra care in handling this value. You should implement some kind of checking on this textbox value. A possible solution is to check against your database schema if the table typed by your user really exists.
You don't tell us which database system are you using so I will show an example using Sql Server
string tableName = textbox1.text;
using(SqlConnection cnn = new SqlConnection(... connectionstring...))
{
cnn.Open();
DataTable dt = cnn.GetSchema("TABLES");
DataRow[] rows = dt.Select("TABLE_NAME = '" + tableName + "'");
if(rows.Length > 0)
{
// Now you are sure to have a valid table in your textbox
// and could use the input value without risking an Sql Injection
string sql = "INSERT INTO [" + tableName + "] ([itemserial]," +
"[itemname],[itemcount],[itemimage]) " +
"VALUES(#itemserial,#itemname,#itemcount,#itemimage)";
.... the remainder of your code that use the query above....
}
else
MessageBox.Show("Please enter a valid name for your table");
Extending this approach you could change your TextBox to a ComboBox with ComboBoxStyle set to DropDownList (to block typing) and fill the ComboBox with the names returned by the GetSchema call above....
tablename = textbox1.text;
sql = string.Format("INSERT INTO {0} ([itemserial],[itemname],[itemcount],[itemimage])VALUES(#itemserial,#itemname,#itemcount,#itemimage)", tablename);
Although I would strongly recommend against this as it allows people to enter whatever they want into that textbox. Something like:
Robert; DROP TABLE Students;--
Which is discussed in more detail here:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
Change your query like this
sql = "INSERT INTO "+tablename+" ([itemserial],[itemname],[itemcount],[itemimage]) VALUES (#itemserial,#itemname,#itemcount,#itemimage)";
Related
I want to create a table name in SQLite based on the user inputted textbox value or a declared string value. For example:
cmd.CommandText = #"CREATE TABLE '"+Machine_Name.Text+"' AS (Date, Cal_Date) VALUES (#Date, #CalDate)";
I'm receiving a newline in constant error right before the AS. I know this may be bad database design but it would be helpful for me to do it this way.
Your query syntax seems to be mixed up.
If you want to create table, you have to provide the column spec (names and datatypes), or if you use create table as, a valid select query has to be used to define the column names/types.
The last part of your statement with the values clause is a valid form for an INSERT, but not for a create table.
See the Documentation here for details.
The syntax to create a table is the following
cmd.CommandText = #"CREATE TABLE '" + newTable + "'" +
"(DATE DATETIME, CAL_DATE VARCHAR(256))";
This of course assumes that your fields are a DateTime and a VarChar.
In other words, after the tablename you put, between parenthesys, the name of the columns and their datatype.
I suggest also to pay particular attention to the value your user types for the name of the new table. This liberty to type anything could be very dangerous and it is the basic building block when a malicious user tries to create an Sql Injection attack.
string ct = "Create table '" + Textbox1.Text +"'(Column1, Column2)";
SQLiteCommand createCommand1 = new SQLiteCommand(ct, sqliteCon);
createCommand1.ExecuteNonQuery();
sqliteCon.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I am trying to pull data from my table based on the button a user clicks, so if they click the 1940's button it will pull all products from that decade but I cant get the query to work. It has to do with the #decade parameter because that is where I am getting the user input from but it doesnt like it when I am trying to choose a column using that parameter
ImageButton decadeBtn = (ImageButton)sender;
var decade = decadeBtn.CommandArgument;
yearHead.InnerText = decade.ToString();
string cmd="";
DataSet ds;
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is null";
}
using (OleDbConnection dbConn = new OleDbConnection(connectionString))
using (OleDbDataAdapter dbCmdDecade = new OleDbDataAdapter(cmd, dbConn))
{
dbConn.Open();
dbCmdDecade.SelectCommand.Parameters.Add("#decade", OleDbType.Integer).Value = decade;
dbCmdDecade.SelectCommand.Parameters.Add("#line", OleDbType.VarChar).Value = productLine;
ds = new DataSet();
dbCmdDecade.Fill(ds, "products");
}
No you can't use a parameter in that way. As a rule, you cannot use a parameter to define a column name or a table name (or concatenating it to form a column name). A parameter could only be used to define a value used in the query. (or with a stored procedure to create an SQL Text inside the sp to be executed but that is another more complex story),
However, assuming that you are not allowing your users to type directly the decade value (Sql Injection vulnerability), then it is pretty simple to create a string with the column name desidered and use it in your query.
Add a method that just concatenate together you decade string with your prefix for the DECADE column
private string GetDecadeColumn(string decade)
{
return "DECADE_" + decade;
}
and in you query
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is null";
}
So ARCHIVE_DECADE_TBL has columns that are named something like DECADE_1990 with a value of 1990, DECADE_2000 with a value of 2000, etc?
It really should be designed to just be called "DECADE" with the value being 1990/2000/etc, but if that's not possible, you'll have to build your query dynamically. I don't believe those parameters will work to set the column name. They can set a value to check for, but not the column names.
You'll have to build the query out manually in c#, so something like:
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_" + decade + #" = #decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
Now, if I misunderstood and your column is actually named DECADE_#decade, then I think you'll just need to change your variable so it's not #decade, so something like #mydecade. The conflict there will confuse it.
Sooooo like...
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#mydecade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
And then down below:
dbCmdDecade.SelectCommand.Parameters.Add("#mydecade", OleDbType.Integer).Value = decade;
That probably shouldn't have an # in the column name though. :)
I have been trying to add a column programmatically in ASP.NET to modify the tables in SQL Server.
Please see the following code:
string suppliernotxt = supplieridlist[1].ToString();
//SqlCommand cmd2 = new SqlCommand("ALTER TABLE [ProductNormalDB] ADD suppliernotxt nvarchar(20) NULL", con);
SqlCommand cmd2 = new SqlCommand("ALTER TABLE ProductNormalDB ADD #supplierlist nvarchar(20) NULL", con);
cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt);
//cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt.ToString());
//cmd2.Parameters["#supplierlist"].Value = supplieridlist[x];
cmd2.ExecuteNonQuery();
supplieridlist is an array that acquires all the column names to add into the SQL Server database. For some reason the parametrized method is not working and shows the following error:
Incorrect syntax near '#supplierlist'.
The basic idea is to have a user select from a check box the name of the suppliers, based on the selected number of suppliers the array will create the supplier names for ex. if we selected 3 suppliers, the array will save "Supplier1", "Supplier2", "Supplier3" and then the SqlCommand is supposed to alter the table and add the new columns.
You cannot use parameters to express the name of columns.
Parameters could only be used to express values for WHERE clause or for INSERT or UPDATE statements.
You could use string concatenation for your query text, passing the string value to a stored procedure or use some form of dynamic sql.
Please be very carefull with these kind of approaches because if you don't keep absolute control on the values passed to your code you will be exposed to Sql Injection.
Adding as an example of Dynamic SQL execution, but still vulnerable to SQL Injection
string suppliernotxt = supplieridlist[1].ToString();
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = '" + suppliernotxt + "'; " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"
SqlCommand cmd2 = new SqlCommand(execSQL, con);
cmd2.ExecuteNonQuery();
As you can see, even with Dynamic SQL there is nothing that prevent an SQL Injection attack passing via the suppliernotxt variable
EDIT As explained in the comments below from #RBarryYoung, a good improvement on the SQL Injection problem for this case of dynamic sql could be the usage of the QUOTENAME function to obtain an Unicode string with the required delimiters around the input string
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = QUOTENAME('" + suppliernotxt + "'); " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"
I want to get a value of a cell from access database where value of "fdne1" column is textBox1.text
in other words I dont know "statment" code in below code what should be
my database columns are fdne1, fee
string statement =??????????? */Select * From Table2 where fdne1 valve is textBox1.text
OleDbCommand MyOleDbComm2 = new OleDbCommand();
ObjConn2.Open();
MyOleDbComm2.CommandText =
"UPDATE Table2 " +
"SET fee="+ statment +
" Where(Table2.fdne1)='" + textBox1.Text + "'";
MyOleDbComm2.Connection = ObjConn2;
MyOleDbComm2.ExecuteNonQuery();
ObjConn2.Close();
My database is access and has 2 tables ,table2 have 2 columns I want to get value of "fee" column in a row that "fdne1" value is somthing like textbox1.text and put it to a string or convert it to int then I do some mathematic processes on it and put the new value on database
I can edit database but I want value of the cell that I said
Sorry for bad English :)
You should know that SQL has some statements like :
Select to select value(s) from table
Update to update value(s) from table
...
If you want to get the value of one cell in the table you should use a select statement .
Like this: Select "your column" from "your table" where "your condition to filter the column"
be aware that the result might return more than one value as for your condition.
If you want to update a value in the table then use an update statement like this:
Update "your table" set "your column=new value" where "your condition to find the value inside the column"
Please be more explicit and I will provide more info.
If I have to I right then I can try to give you some code sample:
OleDbCommand MyOleDbComm2 = new OleDbCommand();
ObjConn2.Open();
MyOleDbComm2.CommandText = "Select fee from table2 " +
" Where Table2.fdne1='" + textBox1.Text + "'";
MyOleDbComm2.Connection = ObjConn2;
var result= MyOleDbComm2.ExecuteScalar();
ObjConn2.Close();
Why don't use Access Query Designer and then copy and paste the SQL ?
I have dynamically generated text-box for which i need to write an insert query into my SQL server 2005 database.
The problem is when i write the insert query i can't include the text-box names as the text-box will be generated run time.
I tried using the following logic:
PLEASE NOTE THAT I WISH TO GENERATE DYNAMIC TEXTBOXES AND THEN A DYNAMIC SQL QUERY.
String str=//will contain a data fetched from all the textboxes generated dynamically and will be seprated using a ','(as in an insert statement).
This string str will be directly passed on to the insert query so that all the values will be taken in directly.
But the logic does not work.
Please help..
A couple of points
Your method leaves you open to SQL injection attacks. This is a bad thing. You should use a sqlCommand object to execute the SQL, using parameter objects to pass in the values to insert, this will guard against SQL Injection attacks.
Name your textboxes after each column in the table your inserting into.
Hope this helps
You need to keep track of your text boxes as they are generated.
List<TextBox> TextBoxes = new List<TextBox>();
...
TextBox DynamicBox1 = new TextBox();
...
TextBoxes.Add(DynamicBox1);
Then if you have the names of your columns somewhere
string Columns = "#col0, #col1, #col2"; //etc
string Query = #"INSERT INTO [Table]
(" + Columns.Replace("#", "") + ")
VALUES (" + Columns+ ")";
using a paramaterized command
SqlCommand Command = new SqlCommand(Query, Connection);
for (int i=0; i<TextBoxes.Count; i++)
{
Command.Parameters.AddWithValue("#col" + i, TextBoxes[i].Text);
}
Connection.Open()
Command.ExecuteNonQuery();
Connection.Close()
I have not added in error handling