how insert value into sql sever using java? - java

sorry if my questions are identical. I was trying to find out online documentation but I still have not solved the problem. it's an error in the line "stmt.executeUpdate ();"
public class DBConnect {
private List<SinhVien> result = new ArrayList<SinhVien>();
public void updateSQL(String masv, String malop, String ten,
Date ngaysinh, String diachi) {
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://MyPC:1433;databasename=QLSV;username=sa;password=APASSWORD");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO SinhVien(masv, malop, ten, ngaysinh, diachi) VALUES(?, ?, ?, ?, ?");
stmt.setString(1, masv);
stmt.setString(2, malop);
stmt.setString(3, ten);
stmt.setDate(4, ngaysinh);
stmt.setString(5, diachi);
stmt.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
DBConnect dbConnect = new DBConnect();
dbConnect.XuatDSSV();
dbConnect.findSinhvienById("51003146");
dbConnect.updateSQL("123", "malop", "ten", null, "diachi");
}

I suggest you store your query in a String. It would have been easier to read, and find the problem...
final String query = "INSERT INTO SinhVien"
+ "(masv, malop, ten, ngaysinh, diachi) "
+ "VALUES(?, ?, ?, ?, ?)"; // <-- You were missing the close paren.
PreparedStatement stmt = connection.prepareStatement(query);

Try to add connection.commit() after stmt.executeUpdate(). And please, post the exception.

Related

Unknown column in jackets in field list

I have been trying to add values to a table named bill_items and this is the coding for the button "add to cart" but it shows and error saying "Unknown column Jacket in field list. What is wrong in this coding?
try {
rs = stmt.executeQuery("select * from mens_wear where Item_code = 1090;");
while(rs.next()){
icode = rs.getInt("Item_code");
p = rs.getInt("Price");
bname = rs.getString("Brand_Name");
iname = rs.getString("Item_Name");
t = rs.getString("Type");
}
rs.close();
stmt.close();
con.close();
} catch(Exception e)
{JOptionPane.showMessageDialog(null,e.getMessage());}
try {
Class.forName("java.sql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/aashita","root","1510");
stmt = con.createStatement();
int a = stmt.executeUpdate("insert into bill_items values('"+icode+"','"+t+"','"+bname+"','"+iname+"','"+p+"');");
JOptionPane.showMessageDialog(null,"Added Successfully");
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}
}
It is a bad practice to not specify column names in an insert and depend on table column order. There could also be an issue with escaping of your query string if any of your values contain quotes. I would try adding the column names and using a prepared statement with parameters.
string updateText = "insert into bill_items (Item_code, Type, Brand_Name, Item_Name, Price) ";
updateText += "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(updateText);
stmt.setInt(1, icode);
stmt.setString(2, t);
stmt.setString(3, bname);
stmt.setString(4, iname);
stmt.setInt(5, p);
int a = stmt.executeUpdate();

Insert multiple data (List) in MySQL using JDBC

I am trying it from last 2 hour i dont know what is going wrong. also let me know how could i test if the connection is successfull or not.. it is for now.. but still i wanted to know..
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 '?, ?)'
My code:
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/medicinedb";
static final String USER = "root";
static final String PASS = "";
static final String DRIVER = "com.mysql.jdbc.Driver";
public boolean saveMedicine(List<MedicineName> medicineName) throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
for (MedicineName element : medicineName) {
String sql;
sql = " insert into medicinename (name, pgurl)" + " values
( ?, ?)";
System.out.println(conn);
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
Why you are using Statement and Prepared statement. You are performing operations with Statement. Thus it does not have value. Remove the Statement
stmt = conn.createStatement();
And do the following
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
//stmt.executeUpdate(sql);
preparedStmt .executeUpdate(sql);
use
String sql = "insert into medicinename (name, pgurl) values (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, element.getName());
preparedStmt.setString (2, element.getPgurl());
preparedStmt.executeUpdate();
you should delete executeUpdate(sql); to executeUpdate();
You mix between your stm and preparedStmt, you have to execute preparedStmt and not stm.
Another thing when you want to executing multiple statements as one unit, its good to work with Statement Batching instead for example :
PreparedStatement preparedStmt;
String sql;
conn.setAutoCommit(false);
for (MedicineName element : medicineName) {
sql = "insert into medicinename (name, pgurl) values (?, ?)";
System.out.println(conn);
preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
preparedStmt.addBatch(sql);
}
preparedStmt.executeBatch();
conn.commit();

No error, but data doesn't get inserted into table

In my database I have two tables called car and ad. In car i have a foreign key referencing the adId value in ad. When i run my code, i don't get any errors, but data is only inserted into ad, not car. Any suggestions? Here's my code:
public void createAd(Ad ad, Car car) {
try {
Class.forName("org.postgresql.Driver");
if (con != null) {
ps = con.prepareStatement("INSERT INTO \"ad\"(\"title\", \"description\", \"author\", \"image\") VALUES (?, ?, ?, ?)");
ps.setString(1, ad.getTitle());
ps.setString(2, ad.getDescription());
ps.setString(3, ad.getAuthor());
ps.setBytes(4, ad.getImage());
ps.executeQuery();
ps = con.prepareStatement("SELECT currval('\"ad_adId_seq\"');");
rs = ps.executeQuery();
rs.next();
int adId = rs.getInt("currval");
ps = con.prepareStatement("INSERT INTO \"ad\"(\"adId\") VALUES (?);");
ps.setInt(1, adId);
ps.executeUpdate();
ad.setAdId(adId);
ps = con.prepareStatement("INSERT INTO \"car\"(\"distanceTraveled\", \"age\", \"condition\", \"vin\", \"brand\", \"price\", \"ad_adId\") VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, car.getDistanceTraveled());
ps.setInt(2, car.getAge());
ps.setString(3, car.getCondition());
ps.setString(4, car.getVIN());
ps.setString(5, car.getBrand());
ps.setInt(6, car.getPrice());
ps.setInt(6, adId);
ps.executeQuery();
car.setAdId(adId);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
There is an error in your last query :
ps.setInt(7, adId);
instead of
ps.setInt(6, adId);
I suggest that you should take a look at spring-database. Using JdbcTemplate will reduce a lot of the JDBC boiler plate code and more important will take care for a lot of jdbc connection leaks worries for you.
If you sill need to use plain JDBC, you need to properly initialize the connection object and use update instead of query, when using update statements.
Also you need to properly close the statement objects that were created.
You should do something similar to the below code:
Connection con = null;
PrepareStatement ps1 = null;
PrepareStatement ps2 = null;
PrepareStatement ps3 = null;
PrepareStatement ps4 = null;
ResultSet rs = null;
String url = "jdbc:postgresql://localhost/dbName";
String user = "userName";
String password = "userPass";
try {
con = DriverManager.getConnection(url, user, password);
ps1 = con.prepareStatement("INSERT INTO \"ad\"(\"title\", \"description\", \"author\", \"image\") VALUES (?, ?, ?, ?)");
ps1.setString(1, ad.getTitle());
ps1.setString(2, ad.getDescription());
ps1.setString(3, ad.getAuthor());
ps1.setBytes(4, ad.getImage());
ps1.executeUpdate();
ps2 = con.prepareStatement("SELECT currval('\"ad_adId_seq\"');");
rs = ps2.executeQuery();
if(rs.next())
int adId = rs.getInt("currval");
}
ps3 = con.prepareStatement("INSERT INTO \"ad\"(\"adId\") VALUES (?);");
ps3.setInt(1, adId);
ps3.executeUpdate();
ad.setAdId(adId);
ps4 = con.prepareStatement("INSERT INTO \"car\"(\"distanceTraveled\", \"age\", \"condition\", \"vin\", \"brand\", \"price\", \"ad_adId\") VALUES (?, ?, ?, ?, ?, ?, ?)");
ps4.setInt(1, car.getDistanceTraveled());
ps4.setInt(2, car.getAge());
ps4.setString(3, car.getCondition());
ps4.setString(4, car.getVIN());
ps4.setString(5, car.getBrand());
ps4.setInt(6, car.getPrice());
ps4.setInt(7, adId);
ps4.executeUpdate();
car.setAdId(adId);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(getClass().getName());
lgr.log(Level.SEVERE, "Unable to execute updates", ex);
} finally {
try {
if (rs != null)
rs.close();
if (ps1 != null)
ps1.close();
if (ps2 != null)
ps2.close();
if (ps3 != null)
ps3.close();
if (ps4 != null)
ps4.close();
if (con != null)
con.close();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(getClass().getName());
lgr.log(Level.WARNING, "Unable to close the connection", ex);
}
}

Java Netbeans MySql database Connection

I want to insert row into MySql database with a normal Program for Mysql connection in Java Netbeans,but when i run this code my database remains unaffected.I had setup connection with Netbeans and Mysql and it is working fine.
Code:
import java.sql.*;
public class MySqlConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/migration";
static final String USER = "root";
static final String PASS = "ngts12345";
public static void main(String[] args) {
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
}catch(Exception e){
//Handle errors for Class.forName
}
}
}
there is not space after format) and values
Change this line to
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
to
String sql = "INSERT INTO document(document_id, document_name, format) " +
"VALUES (?, ?, ?)";
Try doing this:
preparedStatement.executeUpdate(sql);
and you should also specify database
String sql = "INSERT INTO database_name.document (document_id, document_name, format)" +"VALUES (?, ?, ?)";
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","");
String sql = "select * from 'table_name'.database_name where user=? and pass=?";
pst = conn.prepareStatement(sql);
rs= pst.executeQuery();
}
Note preparedStatement.executeUpdate() returns true (record was successful in insert, update, or delete) or false (not successful). Therefore I suggest printing out the result to see if it worked.
As for not getting an error message, are you consuming exceptions and not printing out the error? In your catch block, put e.printStackTrace() to see what the error is.

Inserting variable values into SQL Server using Java

So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. What I wanted to know if there is a way that I can pass those values as variables that I will declare as parameters in the executing method like so:
public void updateSQL(String name, String dnsName, String ipV4, String ipV6, int statusCode)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");
System.out.println("Database Name: " + connection.getMetaData().getDatabaseProductName());
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID)" + "VALUES(#Name, #DNSName, #IPAddressV4, #IPAddressV6, #StatusCodeID)");
System.out.println("Data Inserted");
ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");
while(resultSet.next())
{
System.out.println("Computer Name: " + resultSet.getString("Name"));
}
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("Problem Connecting!");
}
}
I've tried couple of different things but no luck so far. Anyone know if this can be done?
You may use PreparedStatement instead of Statement.
PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();
Using this way, you prevent SQL injection.
Have a look here :
PreparedStatement prep = conn.prepareStatement("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID) VALUES(?, ?, ?, ?, ?)");
prep.setString(1, name);
prep.setString(2, dnsName);
prep.setString(3, ipV4name);
prep.setString(4, ipV6);
prep.setInt(5, statusCode);
prep.executeUpdate();
this will help you understand.

Categories