I want to create another method called public void execute() and run the preparedStmt.executeBatch(); from there, but I don't know how.
public void save() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Sacuvano nov proizvod sa sifrom: " + proizvodID + " Naziv proizvoda: " + naziv));
try {
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/fpis";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "root");
String query = " insert into proizvod values (?, ?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, proizvodID);
preparedStmt.setString(2, naziv);
preparedStmt.setString(3, opis);
preparedStmt.setDouble(4, cena);
preparedStmt.setString(5, jedMere);
preparedStmt.addBatch();
preparedStmt.executeBatch();
conn.close();
} catch (Exception e) {
System.err.println("Greska!");
System.err.println(e.getMessage());
}
}
public void execute(){
{
You should declare PreparedStatement preparedStmt and Connection conn as a attribute of your class.
Like that you could setup preparedStmt in public void save() and conn in your constructor. After that, just call preparedStmt.executeBatch(); from public void execute(); and close conn after.
Related
String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
public void createConnection(int id, String name, String author, String
publisher) {
try {
Connection mycon = DriverManager.getConnection(dburl);
Statement mystmt = mycon.createStatement();
String sql = "insert into addbook" + "(Book ID,Book
Name,Author,Publisher)" + "values" + "(" + id + "," + name + "," +
author + "," + publisher + ")";
mystmt.executeUpdate(sql);
System.out.println("updated");
} catch (Exception ex) {
}
execute update is a method in another class.there seem to be
whats the wrong with this code segment? database is not updating!!
You have not loaded the database drivers, to do that include this code:
Class.forName("com.mysql.jdbc.Driver");
If you haven't drivers download and put in project library.
Their are some problems with this code snippet. One is you didn't load the database. Also you didn't use the username and password.
I recommend you to create the database connection separately. Maybe in a separate Java file. As below,
public class DatabaseConnection {
public static Statement getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver"); //Loading the database
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3307/restaurentsystem","nandika","nandika"); //username and password can save as variables and pass here
Statement statement = c.createStatement();
return statement;
}
}
Then you can use it whenever you want. In this situation,
try {
Statement s = DatabaseConnection.getConnection();
s.executeUpdate("INSERT INTO addbook (Book ID, Book Name, Author, Publisher) VALUES (?, ?, ?, ?);"); //Values should assign here.
System.out.println("updated");
} catch (Exception e) {
System.out.println(e);
}
This is what I do if I do this. I recommend you to try this method.
This is the way you should be doing it, with preparedStatement to prevent injections
String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
private PreparedStatement preparedStatement;
private Connection con = null;
public static void main(String[] args) {
}
public void createConnection(int id, String name, String author, String publisher) {
try {
con = DriverManager.getConnection(dburl, user, password);
String stmt = "INSERT INTO addbook (Book ID,Book Name,Author,Publisher) VALUES (?, ?, ?, ?)";
preparedStatement = con.prepareStatement(stmt);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, author);
preparedStatement.setString(4, publisher);
preparedStatement.executeUpdate();
con.close();
System.out.println("updated");
} catch (Exception ex) {
}
I have just created a method in my class file, were I insert data into my sql database.
1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
Car c = new Car();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, aLicense);
preparedStmt.setInt(2, aJourneys);
preparedStmt.setString(3, aUsername);
preparedStmt.setString(4, aPassword);
preparedStmt.execute();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return c;
}
Calling the method returns an error that the method is not applicable for arguments
//int addingID = Integer.parseInt(enteringID.getText());
String addingReg = enteringReg.getText();
int addingJourneys = Integer.parseInt(enteringJourneys.getText());
String addingUsername = enteringUsername.getText();
#SuppressWarnings("deprecation")
String addingPassword = enteringPassword.getText();
Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
int addStatus = myCar.addVehicle(newCar);
if (addStatus == 1) {
JOptionPane.showMessageDialog(null, "Vehicle Added");
enteringID.setText("(eg. 1-999)");
enteringReg.setText("(eg. - 162-MH-749)");
enteringJourneys.setText("(eg. 7)");
enteringUsername.setText("(eg. - username#domain.com)");
enteringPassword.setText("");
}
else {
JOptionPane.showMessageDialog(null, "Error, Please Try Again");
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, "Error, Please Try Again");
}
}
});
This is not a final answer for your question, but purely to clarify my comment.
If you want your method to return a Car object, you'll have to create an instance of class Car and return it:
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, "'" + aLicense + "'");
preparedStmt.setInt(2, aJourneys);
preparedStmt.setString(3, "'" + aUsername + "'");
preparedStmt.setString(4, "'" + aPassword + "'");
preparedStmt.execute();
conn.close();
Car c = new Car();
//Do anything with the car object that you like.
//for example: c.setColor("blue");
return c;
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
//kayaman is correct here: we still need to return something here in order to be able to compile
return null;
}
Separate the logic!
Use this class to retrieve connection where you need it:
public class DatabaseConnection
{
private static final String CONN_URL = "some connection url";
private static Connection instance = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static synchronized Connection getInstance() throws SQLException
{
if (instance == null)
{
instance = DriverManager.getConnection(CONN_URL);
}
return instance;
}
}
Use it in your function like this:
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword)
{
String sql = "insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword) values (?, ?, ?, ?)";
try (Connection conn = DatabaseConnection.getInstance(); PreparedStatement prepStatement = conn.prepareStatement(sql))
{
Car successfulAdd = new Car();
prepStatement.setString(1, aLicense);
prepStatement.setInt(2, aJourneys);
prepStatement.setString(3, aUsername);
prepStatement.setString(4, aPassword);
if (prepStatement.execute())
{
return successfulAdd;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
I am working with batch prepared statement.
import java.sql.*;
import java.util.Arrays;
public class QryBtch {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
static final String USER = "root";
static final String PASS = "roottoor";
public static void main(String[] args) {
Connection conn = null;
int[] results = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
PreparedStatement ps = null;
String query = "insert into mytable (Emp_ID, Emp_Name) values (?,?)";
ps = conn.prepareStatement(query);
String name1 = "Name1";
String name2="Big Big Name Name 1"; //longer than column length
String name3="Name2";
ps.setInt(1, 1);
ps.setString(2, name1);
ps.addBatch();
ps.setInt(1, 2);
ps.setString(2, name2);
ps.addBatch();
ps.setInt(1, 3);
ps.setString(2, name3);
ps.addBatch();
results = ps.executeBatch();
System.out.println(Arrays.toString(results));
conn.close();
}catch(SQLException se){
System.out.println(Arrays.toString(results));
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
I am trying to insert into a table having name defined as 8 character. So as expected my second statement got failed. Is it possible to track the statement that has been failed or the bind values for error handling.
I want to look for something that matches a enum: Divisions:U6,U7,U8...
It works when i do this.
public ArrayList<Training> zoekTrainingen(Ploegen p) throws
ApplicationException {
ArrayList<Training> tr = new ArrayList<>();
Connection conn = ConnectionManager.getConnection(driver,
dburl, login, paswoord);
try (PreparedStatement stmt = conn.prepareStatement(
"select * from trainingen");) {
stmt.execute();
ResultSet r = stmt.getResultSet();
while (r.next()) {
---
}
} catch (SQLException sqlEx) {
throw new ApplicationException("");
}
finally {
return tr;
}
}
}
but when I do this:
try (PreparedStatement stmt = conn.prepareStatement(
"select * from trainingen where Divsion = ?");) {
stmt.setString(1, p.getDivision());
I get nothing
The code is attempting to set a String parameter using an Enum. It should get the String value of the Enum and pass to the setString method.
try (PreparedStatement stmt = conn.prepareStatement(
"select * from trainingen where Divsion = ?");) {
stmt.setString(1, p.getDivision().toString());
Hi I have this method below which should insert values into my database. However I am getting a Null Pointer Exception on the PreparedStatement line
public void insertReservation(String name, String phone, int size, String date, String time, String additionalRequirements, String memberID, String themeID) throws SQLException, ClassNotFoundException {
try {
String strQuery = "INSERT INTO reservation VALUES (?, ? ,?, TO_DATE(?, 'dd-MMM-yy'), ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(strQuery);/
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setInt(3, size);
stmt.setString(4, date);
stmt.setString(5, time);
stmt.setString(6, additionalRequirements);
stmt.setString(7, memberID);
stmt.setString(8, themeID);
results = stmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}//end try
}
Am I inserting this correctly into my database? I am not sure why I am getting this null pointer exeception error.
conn is null, print its value.
Don't know but try this
String strQuery = "insert into reservation(ColumnName1, ColumnName2 ,ColumnName3,) values(?,?,?)";
and at the end it will be only execute();
like this stmt.execute();
executeQuery(); statement works with select query Only
Secondly have you described conn value in constructor or method in which ever class you are using the query if you have than assign it like this conn= SqlConnection.ConnecrDb();
below is the SqlConnection Seperate class i have created
public class SqlConnection {
Connection conn=null;
public static Connection ConnecrDb(){
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn= DriverManager.getConnection("jdbc:odbc:Test","","");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Hope it will help you