Click here to Skip to main content
15,031,495 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Sir,


In my project I want to insert a data to a table from another table in the database.

For that I wrote the query as follows

String str = "insert into branch(Code,Name,metro,state)values ('" + this.txtbranchcode.Text + "','" + this.txtbranchname.Text + "','" + this.cmbmetro.SelectedIndex + "','" + "select code from state where Name='" + this.statename.Text + "'" + "')";


here it shows run time error as incorrect syntax near statename

Pls correct me the error
Posted

wrote:
String str = "insert into branch(Code,Name,metro,state)values ('" + this.txtbranchcode.Text + "','" + this.txtbranchname.Text + "','" + this.cmbmetro.SelectedIndex + "','" + "select code from state where Name='" + this.statename.Text + "'" + "')";


Let's ignore what an utter disaster this is. I hope no-one is actually going to use this code because it is badly put together and not secure at all.

insert into branch(Code,Name,metro,state)values ('Text','Text','SelectedIndex','select code from state where Name='Text'')

You're trying to do what would be best done with a stored proc. You are basically assuming that the number stored as metro is a string ( as it's in quotes ) and that state is also a string, but the string you're trying to store is SQL, and because of double use of ', it's not even valid as a string to store. You should write a stored proc which looks up the state value, then uses it in the insert. You should remove the quotes if metro is a number. You should probably not make the number that you store reliant on the index of a UI element. You definitely need to learn about SQL injection, and write a proper data layer instead of putting SQL in your presentation layer.

Overall, you probably need to read a book on SQL.
   
You need to revisit your quotes. Your present query looks like this -
,'select code from state where Name = 'xxx''.

Fetch the value of code in select code from state where Name='xxx' in a separate query and add just the return value to the one above.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900