0

I am using Netbeans and in this method I have som String and int variables that I would like to insert in the MySQL database.

I have tried this, but still it wont work.

String sql = "INSERT INTO cars (Manufacturer, Color, Extra, Country, Price)" "VALUES (variableManufacturer, variableColor, variableExtra, variableCountry, variablePrice)";

Table name Cars

Colummns Manufacturer, Color, Extra, Country, Price

All the colummns are VARCHAR, except Price, it is an int.

Netbeans crashes, and it says that it cannot find variables. Anyone?

Kumar Saurabh
  • 2,297
  • 5
  • 29
  • 43
Luke
  • 31
  • 1
  • 6

4 Answers4

0

Try this

String sql = "INSERT INTO cars(Manufacturer, Color, Extra, Country, Price) VALUES(variableManufacturer, variableColor, variableExtra, variableCountry, variablePrice)";

Update

i think this link can help you

Inserting records into a MySQL table using Java

Community
  • 1
  • 1
E.Solicito
  • 101
  • 9
  • I don't think it will work either, because the variables need to be taken cared of in some other way, maybe with + * ' or something. – Luke Nov 24 '15 at 09:49
0

Try this:

String sql = "INSERT INTO cars (Manufacturer, Color, Extra, Country, Price)";

sql + = "  VALUES (variableManufacturer, variableColor, variableExtra, variableCountry, variablePrice)";
Saharcasm
  • 148
  • 1
  • 8
  • I don't think it will work either, because the variables need to be taken cared of in some other way, maybe with + * ' or something. – Luke Nov 24 '15 at 09:51
0

Try this :)

String sql = "INSERT INTO cars (Manufacturer, Color, Extra, Country, Price) "
+ "VALUES ('"+variableManufacturer+"', '"+variableColor+"',
           '"+variableExtra+"', '" +variableCountry +"', 
           "+variablePrice+")";
Vishnu
  • 375
  • 4
  • 16
  • This answer is considered bad practice as it is open to SQL injection attacks. – CBreeze Nov 24 '15 at 10:14
  • @user5165120 I would strongly recommend referring to my answer and not use this approach. You will be open to SQL injection attacks in the future and it is bad practice. – CBreeze Nov 24 '15 at 10:38
0

What you're looking for is a PreparedStatement in Java.

Something like;

PreparedStatement ps = connection.prepareStatement("INSERT INTO cars (Manufacturer, Color, Extra, Country, Price) VALUES (?,?,?,?,?)");

You would then use the ps.SetXX() method with your variables, in your case being VARCHAR which I believe falls into the String conversion type: JDBC - How to set char in a prepared statement

Community
  • 1
  • 1
CBreeze
  • 2,925
  • 4
  • 38
  • 93