create and insert values using mysql JDBC - java

I have the sample code.
public void UpdateTable1() {
for (int t = 0; t < 20; t++) {
if (consumer == 1 && number == 1 && provider1 == 31 && feedback == 1) {
try {
Class.forName(driverName);
con = DriverManager.getConnection(url + dbName, "root", "mysql");
try {
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT Consumer1 VALUES ("
+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
System.out.println("1 row affected");
} catch (SQLException s) {
System.out.println("SQL statement is not executed!");
}
con.close();
}
}
}
}
I want to insert the same set of values(31,printer,1) into the table consumer2,consumer3.Is it possible without using another try catch statements...Please help me.

I hope I'm not offending, but are you sure you fully understand how try-catch works?
The reason that the try catch statement is inside the for for t loop, is (likely) that someone wanted to ensure that one failure will not prevent other iterations of the loop from taking place. You could end up with corrupted data that way.
The decision you have to make is whether you want to do all three insertions under the same try-catch or not.
To easily do three insertions, do a loop on i from 1 to 3, and every time create a different statement, by adding strings, so that the first time the table is Consumer1, the second time it is Consumer2, etc. Put the whole loop inside the try catch, or put the-try-catch inside the body of the loop.

You could replace
"INSERT Consumer1 VALUES ("
with
"INSERT INTO Consumer" + (t + 1) + " VALUES ("

I'm a little unclear on this one. Is there some restriction on how many statements you can create per connection? Or will the connection close down after each update is executed?
If not, then this should work
Statement st2 = con.createStatement();
int val = st.executeUpdate("INSERT Consumer2 VALUES ("+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
Statement st3 = con.createStatement();
int val = st.executeUpdate("INSERT Consumer3 VALUES ("+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
if the connection closes down or you can only do one statement at a time, then I guess you could move the whole thing to a private method and then call it with different parameters, something like:
private boolean doInsert(String tableName) {
con = DriverManager.getConnection(url + dbName, "root", "mysql");
try {
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT " + tableName + " VALUES ("
+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
System.out.println("1 row affected");
return true;
} catch (SQLException s) {
System.out.println("SQL statement is not executed!");
return false;
}
}

Related

I'm working on databases in my java class, and I need help figuring out how to update a specific value/column in the database

Here is my first class. This is where im building my table and plugging in some values. In the second class, I am only displaying firstName,lastName, and salary BUT I also need to display the salary once more, but this time adding an increase of 10%, or salary += salary*.1 to be clear
public class CreateEmployeeDB
{
public static void main(String[] args)
{
final String DB_URL = "jdbc:derby:EmployeeDB;create=true";
try
{
Connection conn =
DriverManager.getConnection(DB_URL);
dropTables(conn);
buildEmployees(conn);
conn.close();
}
catch (Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
public static void dropTables(Connection conn)
{
try
{
// Get a Statement object.
Statement stmt = conn.createStatement();
try
{
stmt.execute("DROP TABLE Employees");
}
catch(SQLException ex)
{
// No need to report an error.
// The table simply did not exist.
}
}
catch(SQLException ex)
{
System.out.println("ERROR: " + ex.getMessage());
ex.printStackTrace();
}
}
public static void buildEmployees(Connection conn)
{
try
{
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE Employees (" +
"socialSecurityNumber VARCHAR(30) NOT NULL PRIMARY KEY, " +
"firstName VARCHAR(30), " +
"lastName VARCHAR(30), " +
"weeklySalary DOUBLE, " +
"birthday DATE, " +
"employeeType VARCHAR(30), " +
"departmentName VARCHAR(30) " +
")");
stmt.execute("INSERT INTO EMPLOYEES VALUES( " +
"'11-1111', " +
"'John', " +
"'Smith', " +
"1000.50, " +
"'1945-01-02', " +
"'salariedEmployee', " +
"'R&D')");
stmt.execute("INSERT INTO EMPLOYEES VALUES( " +
"'22-2222', " +
"'Sue', " +
"'Jones', " +
"865.00, " +
"'1961-02-03', " +
"'commissionEmployee', " +
"'SALES')");
stmt.execute("INSERT INTO EMPLOYEES VALUES( " +
"'33-3333', " +
"'Bob', " +
"'Lowis', " +
"950.25, " +
"'1958-10-05', " +
"'basePlusEmployee', " +
"'SALES')");
stmt.execute("INSERT INTO EMPLOYEES VALUES( " +
"'44-4444', " +
"'Karen', " +
"'Price', " +
"1100.15, " +
"'1972-05-25', " +
"'salariedEmployee', " +
"'HR')");
}
catch (SQLException ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
}
here is my second class. How do I update the salary in here? I'm assuming I need to do something with SELECT? But I can't quite figure it out.
public class UpdateSalary
{
public static void main(String[] args)
{
final String DB_URL = "jdbc:derby:EmployeeDB";
try
{
Connection conn = DriverManager.getConnection(DB_URL);
showSalary(conn);
updateSalary(conn);
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
public static void showSalary(Connection conn)
{
final String DB_URL = "jdbc:derby:Personnel";
try
{
Statement stmt = conn.createStatement();
String sqlStatement = "SELECT * FROM Employees";
ResultSet result = stmt.executeQuery(sqlStatement);
System.out.println("\n\t\t\t\t Employees Report - Current Salary ");
System.out.println("-------------------------------");
System.out.println("\t\t\t First \t\t\tLast Salary");
while (result.next())
{
System.out.printf("%30s %30s $%5.2f\n",
result.getString("firstName"),
result.getString("lastName"),
result.getDouble("weeklySalary")
);
}
//conn.close();
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
public static void updateSalary(Connection conn)
{
final String DB_URL = "jdbc:derby:Personnel";
try
{
Statement stmt = conn.createStatement();
String sqlStatement = "SELECT weeklySalary FROM Employees ";
ResultSet result = stmt.executeQuery(sqlStatement);
System.out.println("\n\t\t\t\t Employees Report - Updated Salary ");
System.out.println("----------------------------------");
System.out.println("\t\t\t First \t\t\tLast Salary");
while (result.next())
{
System.out.printf("%30s %30s $%5.2f\n",
result.getString("firstName"),
result.getString("lastName"),
result.getDouble("weeklySalary")
);
}
conn.close();
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
}
i apologize for the messy code and weird formatting that you get in the output. If anyone has tips, I would appreciate it. Thank you for your time.
You can SELECT it by making the relevant changes and display the result directly. Although this does not affect the database's weeklySalary values.
SELECT firstName,lastName,weeklySalary*1.1 as weeklySalary FROM Employees
You can create a SQL statement using UPDATE with the updated salary value and then execute the SQL statement using executeUpdate(). This will update the Database's weeklySalary values. Then, simply display the result.
Under updateSalary(Connection conn) replace in accordance.
String updateSqlStatement = "UPDATE Employees SET weeklySalary = weeklySalary*1.1";
stmt.executeUpdate(updateSqlStatement);
String sqlStatement = "SELECT * FROM Employees";
ResultSet result = stmt.executeQuery(sqlStatement);

java.lang.ArrayIndexOutOfBoundsException object array

Hi I am trying to create a program that collects tasks from a database and displays them for editing. There is an issue that I am not sure how to resolve.
I want to load the several task objects with info from the database. The error only shows up when the program is actually ran.
This is the error:
Please enter a corresponding number: 2
This works? 1
5.6.25-log
This works? 2
This works? 3
This works? 4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at mytaskapp.DatabaseConnectTaskSelect.Connect(DatabaseConnectTaskSelect.java:65)
at mytaskapp.Display.TaskOutput(Display.java:175)
at mytaskapp.Display.StartScreen(Display.java:51)
at mytaskapp.MyTaskApp.main(MyTaskApp.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
My code is
public static void Connect()
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
Statement stu = null;
ResultSet rsu = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/tasks";
String user = "root";
String password = "cinder";
try {
int index = 1;
TaskObject[] task = new TaskObject[index];
System.out.println("This works? 1");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
System.out.println("This works? 2");
pst = con.prepareStatement("SELECT mainTaskString, timeCreated, dateCreated, timeDue, dateDue, "
+ "notes, project, catagory, taskLength, priority, remind1TimeDue, remind1DateDue, "
+ "remind2TimeDue, remind2DateDue FROM usertasks");
rsu = pst.executeQuery();
System.out.println("This works? 3");
while (rsu.next()) {
index = 1;
//task[index] = new TaskObject(index);
System.out.println("This works? 4");
task[index].setTask(rsu.getString("mainTaskString"));
System.out.println("This works? 4.1");
task[index].setDateCreated(rsu.getString("timeCreated") + " " + rsu.getString("dateCreated"));
System.out.println("This works? 4.2");
task[index].setDateDue(rsu.getString("timeDue") + " " + rsu.getString("dateDue"));
System.out.println("This works? 4.3");
task[index].setNotes(rsu.getString("notes"));
task[index].setProject(rsu.getString("project"));
task[index].setCatagory(rsu.getString("catagory"));
task[index].setTaskLength(rsu.getInt("taskLength"));
task[index].setPriority(rsu.getInt("priority"));
task[index].setRemind1DateDue(rsu.getString("remind1TimeDue") + " " + rsu.getString("remind1DateDue"));
task[index].setRemind2DateDue(rsu.getString("remind2TimeDue") + " " + rsu.getString("remind2DateDue"));
System.out.println("This works? 5");
System.out.println("Your Task: " + task[index].getTask() + "\n" + " Date Created: " + task[index].getDateCreated() + " Date Due: " + task[index].getDateDue() +
" Your Notes: " + task[index].getNotes() + "\n" + " Project: " + task[index].getProject() + " Catagory: " + task[index].getCatagory() + " The minutes needed to complete: " + task[index].getTaskLength() +
" Priority: " + task[index].getPriority() + " Reminder 1: " +
task[index].getRemind1DateDue() + " Reminder 2: " + task[index].getRemind2DateDue() + "\n");
System.out.println("This works? 6");
//index++;
}
You can define size of Array only once. So make sure you define it proper otherwise it will throw ArrayIndexOutOfBoundsException when you try to put values more then specified in the size.
In your code you have specified size as 1. So when you try to put more then 1 value in your task array, you will get this exception.
So make sure you specify enough size say 50.
But I would recommend to use List instead of Array, as it gives flexibility automatically increase size without specifying size. You can refer Array or List in Java.
You can make following changes in your code
Declare taskList instead of task array.
List<TaskObject> taskList = new ArrayList<TaskObject>();
In while loop create object of TaskObject, set values into it and then add it to taskList.
TaskObject taskObject = null;
while (rsu.next()) {
taskObject = new TaskObject();
taskObject.setTask(rsu.getString("mainTaskString"));
//set remaining value
//Add taskObject in List
taskList.add(taskObject);
}
int index = 1;
TaskObject[] task = new TaskObject[index];
This will create the array of the object of type TaskObject with the size 1. That means it can have only task[0]. If you give task[1] it is array out of bound.
So in the while loop it should be (according to your exp)
index = 0;
System.out.println("This works? 4");
task[index].setTask(rsu.getString("mainTaskString"));
If your query is returning fixed number of rows then it is advisable to use array else use arraylist.

I have a basic Update Where statement that is sytaxticly correct but does not update the table

This is the code:
#Override public void update(){
Statement stmt = null;
String company = "";
try {
Connect conn = new Connect();
stmt = conn.makeStatement();
// This creates the SQL statement to update an existing student.
System.out.println("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.execute("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("Unable to update employee in the database.");
} finally {
}
System.out.println("Employee successfully updated to the database.");
}
I am assuming I have missed something simple & obvious that i just can't see.
This query doesn't update anything - it just sets a whole lot of columns to their existing values. If you want to update them to something else, you'd better pass those "something else" values in somehow.
Two things I note, you probably want a space between getEmployeeID() and Limit 1; Also, assuming you're not running with autoCommit enabled, you need to call Connection.commit(). Finally, you should close your connection and statement objects in the finally block.

How to insert NULL in mysql especially INT dataType

I have 80000 recodes that are need to insert into database especially in table: temp(ts, temp)
temp is INT.
The problem is almost 20000 recodes are null, so I am wondering how to insert NULL into DB when dataType is INT.
I tried this:
String val = null;
//insert(ts, val) into temp
String sql = "INSERT INTO temp" + "(val)" + " VALUES" + "('" + val + "')";
Statement st = (Statement) conn.createStatement();
count = st.executeUpdate(sql);
unfortunately insert is failure. Print out the exception message:
Incorrect integer value: 'null' for column 'val' at row 1"
Wish someone can help me with it. Thank you.
You should use a PreparedStatement and use setNull(int, int):
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
if (/* int value is not null */) {
st.setInt(1, value);
} else {
set.setNull(1, Types.INTEGER);
}
count = st.executeUpdate();
As an alternative to Mark Rotteveel's answer, you can also use PreparedStatement.setObject(int, Object, int).
You specify the SQL Type (3rd Parameter), and if the object is null, it inserts a null automatically. It's faster and easier.
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
st.setObject(1, value, Types.INTEGER);
count = st.executeUpdate();
You should consider using prepared statements. If you do, you'll find information on how to deal with nulls here and elsewhere.
If you're 100% sure your val value is clean and won't cause SQL Injection (rare, but possible), then the "built string" approach needs to explicitly use null when defining the value:
String sql = "INSERT INTO temp (val) VALUES (";
if (val == null) {
sql += "null";
} else {
sql += val;
}
sql += ")";
I have solved this problem.
The codes update as following:
String sql= null;
if(val.isEmpty()){
System.out.println(val);
System.out.println("Insert ts: " + ts + " val: null");
sql= "INSERT INTO " + table + "(ts,val,pointId)" + " VALUES" + "(" + "'" + ts + "'" + ", " + "NULL" + " , " + "'" + pointId + "'" + ")";
}
else{
System.out.println("Insert ts: " + ts + " val: " + val);
sql= "INSERT INTO " + table + "(ts,val,pointId)" + " VALUES" + "(" + "'" + ts + "'" + ", " + "'" + val + "'" + ", " + "'" + pointId + "'" + ")";
}
Statement st = (Statement) conn.createStatement(); //create the instances of statement
count = st.executeUpdate(sql);
Basically, if insert null into database, just do insert into table(val) value(NULL).
You should explicitly CAST the NULL as an INT
...VALUES(...CAST(NULL AS INT)
It sounds like your are sending "null" in when you should be sending an int. Perhaps try something like
(val == null ? "" : val)

JDBC Oracle Query. Slow when executing with setInt() instead of setObject()

I have the following fragment of code:
public static void main(String[] args) throws SQLException {
Connection c = getConnection();
long time = System.currentTimeMillis();
PreparedStatement ps = c.prepareStatement(sqlQuery);
int index = 1;
for (String param: parameters) {
if (isInt(param)) {
//ps.setInt(index++, Integer.parseInt(param));
ps.setObject(index++, Integer.parseInt(param), java.sql.Types.NUMERIC , 0);
} else {
ps.setString(index++, param);
}
}
displayResult(ps.executeQuery());
System.out.println("It took " + (System.currentTimeMillis()-time) + ".");
time = System.currentTimeMillis();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(expandParametersInStatement(sqlQuery, parameters));
displayResult(rs);
System.out.println("It took " + (System.currentTimeMillis()-time) + ".");
}
The query executed with a PreparedStatement is slower by a factor of 4000. Compared to the Statement approach. They give the same result and the order of execution makes no huge difference.
Using the setObject() instead of setInt() makes the PreparedStatement as fast as the Statement.
What is the difference? The cast in the Database cannot be that expensive? The data type in the database is a NUMBER(10). I guess it is a matter of the indeces which are used. However, I cannot replicate this in the SQL Developer with CAST(x AS INTEGER)?
Thanks.
The statement is:
private static String sqlQuery = "SELECT sum(value) " +
"FROM a monat, " +
" n jahr, " +
" kunde kunde " +
"WHERE monat.kunde_nr IN " +
" (SELECT DISTINCT kunde.kunde_nr " +
" FROM MASKE_4_KUNDEN kunde " +
" WHERE kunde.firma_nr = ? " +
" AND kunde.verkaufsbereich_nr = ? " +
" AND kunde.vertriebsbereich_nr BETWEEN (CASE WHEN ? <> -1 THEN ? ELSE -9999999999 END) AND (CASE WHEN ? <> -1 THEN ? ELSE 9999999999 END) " +
" AND kunde.vertreter_nr BETWEEN (CASE WHEN ? <> -1 THEN ? ELSE -9999999999 END) AND (CASE WHEN ? <> -1 THEN ? ELSE 9999999999 END)" +
" AND kunde.konzern_nr BETWEEN (CASE WHEN ? <> -1 THEN ? ELSE -9999999999 END) AND (CASE WHEN ? <> -1 THEN ? ELSE 9999999999 END) " +
" AND kunde.geschaeftsjahr = ? " +
" AND kunde.kunde_nr BETWEEN (CASE WHEN ? <> -1 THEN ? ELSE -9999999999 END) AND (CASE WHEN ? <> -1 THEN ? ELSE 9999999999 END))" +
" AND monat.firma_nr = ? " +
" AND monat.verkaufsbereich_nr = ? " +
" AND monat.jahr_nr = ? " +
" AND jahr.kunde_nr = monat.kunde_nr " +
" AND jahr.firma_nr = monat.firma_nr " +
" AND jahr.jahr_nr = monat.jahr_nr " +
" AND jahr.verkaufsbereich_nr = monat.verkaufsbereich_nr " +
" AND kunde.kunde_nr = monat.kunde_nr " +
" AND kunde.firma_nr = monat.firma_nr";
setInt() method receives int as a second parameter (not Integer). now, I know that auto-boxing should work but apparently it doesn't always work: http://www.coderanch.com/t/550628/JDBC/java/setInt-String-int-Lost
My guess is that it didn't work in older versions of JDBC and it works in newer versions but is still buggy...
I would try using Integer.intValue() and see if it works any better!
If anyone has more input in regards - I'd love to hear it!
We observed the same behavior also with a prepared statement having just setString() statements over an Oracle Database 10.2.0.4.0.
The problem has been completely solved updating the jdbc driver from 10.2.0.3.0 to 10.2.0.4.0

Categories