To generate data into insert statement - java

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...");
stmt = conn.createStatement();
for (int j = 0; j < 30; j++)
{
int a = 230 + j % 15;
String String = Integer.toString(a);
String str = Integer.toString(a);
double b = 1.3 + j % 17 * 0.1;
String aString = Double.toString(b);
String IKW2 = String.valueOf(b);
String sql ="INSERT INTO cmd";
sql +="VALUES" + "("+ a +b ")";
stmt.executeUpdate(sql);
}
catch(SQLException se){
se.printStackTrace();
}
Here i have done jdbc connection and want to import data
into mysql. So used insert statement .In stack trace its
showing that the connection is done bt there is syntaxerrorexception.
i want to generate data and then want to print all the data to import
in db. Is my insert query is wrong??

You shall use Prepared Statements. Following steps shall help you.
Pre calculate all your column values a, b,c etc.
Create a Prepared Statement (assuming three columns in table)
PreparedStatement ps = con.prepareStatement("INSERT INTO CMD VALUES(?,?,?)");
set parameter values using PreparedStatement#setXXX methods
execute prepared statement

Related

how to execute prepared statement in a for loop to fetch data from tables in jsp?

what is wrong in this code? I am getting this error.
java.sql.SQLSyntaxErrorException: 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 'attendance where sub_id='3' and reg_no='1111'' at line 1
Code
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "*****");
int k;
String sub = "";
int t_class[] = new int[counter];
int att_class[] = new int[counter];
int tallo_class[] = new int[counter];
PreparedStatement ps3;
PreparedStatement ps4;
PreparedStatement ps5;
for (k = 0; k < (counter - 1); k++) {
sub = subjects_id[k];
//START : getting total no of classes held
ps3 = con.prepareStatement("SELECT COUNT(*) FORM attendance where sub_id=? and reg_no=?");
ps3.setString(1, sub);
ps3.setString(2, reg_no);
ResultSet rs3 = ps3.executeQuery();
rs3.next();
t_class[k] = rs3.getInt(1);
}
}
So one big tip is you want to prepare your statement outside of the loop. That is kind of the point of preparing it(Also, parameterizing the inputs). You can re-use the statement, then as stated above you misspelled the word FROM.
PreparedStatement statement = con.prepareStatement("SELECT COUNT(*) FROM attendance where sub_id=? and reg_no=?");
for (int i = 0; i < (k - 1); i++) {
statement.setString(1, sub);
statement.setString(2, reg_no);
ResultSet rs3 = ps3.executeQuery();
rs3.next();
t_class[k] = rs3.getInt(1);
}
There is a typo in your SQL query. You have given FROM as FORM. It should be
ps3 = con.prepareStatement("SELECT COUNT(*) FROM attendance where sub_id=? and reg_no=?");
Also since you are using the same PreparedStatement throughout the loop, then its better you keep the PreparedStatement outside the loop. If you have sql statment which keeps changing inside the loop, then only its worth using it in the loop. If its keep changing, then just use Statement instead of PreparedStatement, else the very purpose of PreparedStatement is lost as you keep changing it.
It should be FROM instead of FORM. The error message clearly indicates that the issue is after the required FROM keyword.
ps3 = con.prepareStatement("SELECT COUNT(*) FROM attendance where sub_id=? and reg_no=?");

JDBC connection to MySQL and Sybase database at same time

I am trying to retrieve data from SYBASE database and copy retrieved data in a table in MySQL. I am able to connect both databases separately (i.e) using jTDS driver for SYBASE and Jdbc_driver for MySQL.
Now I want to connect both databases simultaneously in a single program. But I confused what should be written in Class.forName().
I have used Class.forName(JDBC_DRIVER); for MySQL and Class.forName("net.sourceforge.jtds.jdbc.Driver"); for SYBASE.
Sybase:
public static void main(String[] args) {
String a;
String b;
String c;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:jtds:sybase://10.159.252.29:4100/fmdb","sa","Changeme_123");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("selecttbl_alm_log_2000000000.Csn,"
+ "tbl_alm_log_2000000000.IsCleared,"
+ "tbl_alm_log_2000000000.Id"
+ "From fmdb.dbo.tbl_alm_log_2000000000"
+ "Where IsCleared = 0");
while(rs.next()) {
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
System.out.println(a+" "+b+" "+c);
}
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
MySQL:
try {
Class.forName(JDBC_DRIVER);
System.out.println("connecting to database");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("connected to database successfully");
System.out.println("creating table in given database");
// stmt = conn.createStatement();
String sql = "CREATE TABLE newtable "
+ "(id INTEGER not NULL, "
+ "first VARCHAR(255), "
+ "PRIMARY KEY ( id ))";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println("created table in database");
}
These are just snippets. I am just trying to merge above code.
Help me by telling if this is possible or not and sharing some insights into this.
Multiple connections in a single program, can be created like this
public static void main(String[] args) {
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con1 = DriverManager.getConnection("jdbc:jtds:sybase://10.159.252.29:4100/fmdb","sa","Changeme_123");
Class.forName(JDBC_DRIVER);
Connection con2 = DriverManager.getConnection(DB_URL, USER, PASS);
///After getting both connections, write your code
String a;
String b;
String c;
Statement stmt= con1.createStatement();
ResultSet rs=stmt.executeQuery("select tbl_alm_log_2000000000.Csn, tbl_alm_log_2000000000.IsCleared, tbl_alm_log_2000000000.Id From fmdb.dbo.tbl_alm_log_2000000000 Where IsCleared = 0");
while(rs.next()) ///If your query result is single row, use if instead of while
{
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
System.out.println(a+" "+b+" "+c);
}
String sql = "CREATE TABLE newtable " + "(id INTEGER not NULL, " + "first VARCHAR(255), " + "PRIMARY KEY ( id ))";
stmt = con2.prepareStatement(sql);
stmt.executeUpdate(sql);
con1.close();
con2.close();
}catch(Exception e){ System.out.println(e);}
}
}
the suggestion is to divide a complex task into smaller and more simple tasks:
1)create a method readDB(int startReading, int endReading)with return as ResultSet
2)create a method writeDB(ResultSet result)
3)create a method createTableDB()
P.S. readDB is close to your first example and have to return the read of db, writeDB have only to write inside a db some tutorial, and then createTableDB have to make the table on db like you write in your second example.
pseudo final code, in main:
createTableDB();
// it's good to make a loop for next part:
ResultSet read1=readDB(0,200);
writeDB(read1);
ResultSet read2=readDB(200,400);
writeDB(read2);
ResultSet read3=readDB(400,....); //to the end of db
writeDB(read3);
this is a realy simple solution, it is not perfect and can be modified according to your needs.

Unable to create/modify sqlite tables from Java application

I have a basic java application and a sqlite DB.
I can create table manually through sqLite browser. And I am able to access these tables from my JAVA application.
E.g. Reading from existing table: (I have omitted the try catch blocks in the sample below just to reduce the length of question)
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "select * from test1 where uname = ? and name = user1";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "test");
resultSet = preparedStatement.executeQuery();
if(resultSet.next())
return true;
else
return false;
I am able to perform this query successfully.
However, if I create / modify a table, changes does not show up in SQlite DB (I am viewing db in sqLite browser). If I copy paste the same query in SQlite browser, the query runs successfully and a row is added.
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "INSERT INTO COMPANY (ID,NAME,AGE) VALUES (3, 'tOM', 32);";
preparedStatement = connection.prepareStatement(query);
preparedStatement.executeUpdate();
Am I missing something?
EDIT: Both the above tables exist in my sqlite db. Both were created through sqlite browser
EDIT2: I was getting true from my example 1 above, that's why I felt that I am able to read from db. I update my code to print the data read and nothing gets printed which means I am not able to read the data as well:
resultSet = preparedStatement.executeQuery("SELECT * FROM test1");
and
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
The connection string is:
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\akshay\\sqlite_test.sqlite");
conn.setAutoCommit(true);
return conn;

Using variables to create SQL statements

I'm trying to make a sql query builder type program that uses user input data to build custom queries for the table
so far i have
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
// preparedStmt.setString (2, t2);
// preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
So it connects and everything fine but it doesnt execute the query saying something wrong with the sql syntax for values(?,?,?)
Any help would be awesome thanks guys!!
Carl
Try this, Changes in query and in setting prepared statement parameters,
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between ? and ?"
+ "AND id = ?";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
preparedStmt.setString (2, t2);
preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
Share the exact error if doesn't work for you.
Change this:
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
According to the database syntax that you are using. For example if you using a webserver with Mysql go and type the query to see where the typo is. (if you using mysql it needs dancers to every table)
First, you seem to have edited this method many times to try fix the problem, which has left it in a confused state.
remove the "values (?)" from the sql statement, it does not belong here, it seems to be left over from a prepared insert statement.
call preparedStmt.executeQuery() with zero arguments, you have already supplied it with the sql string and only call it ONCE, you assign a value to rs twice.
your sql statement should contain exactly three question marks, try
select count(*) from dancers where ts between ? and ? and id = ?
next call preparedStmt.setString() three times to supply values t1, t2 and id.
Also, remember to close the connection object in the finally block.

Data writing error

I'm inserting some data into a mySql database. For some unknown reason the data is not being inserted into my table. This worked fine with SQLITE.
Here is my code:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String query1 = "insert into Project (uniqueid,name,address,startingdate,estcompletion,engname) values(?,?,?,?,?,?)";
String query2 = "insert into EngineerData (UniqueId,Name,Password) values(?,?,?)";
String query3 = "insert into " +tableName +" (UniqueId,Category,Item,EstimatedQuantity,Unit,UnitPrice,TotalPrice,TotalSpent) values(?,?,?,?,?,?,?,?)";
String query4 = "insert into ProjectImages (uniqueId, Path) values(?,?)";
PreparedStatement pst1= conn.prepareStatement(query1);
PreparedStatement pst2 = conn.prepareStatement(query2);
PreparedStatement pst3 = conn.prepareStatement(query3);
PreparedStatement pst4 = conn.prepareStatement(query4);
pst1.setInt(1, uniqueID);
pst1.setString(2, projectName.getText());
pst1.setString(3, address.getText());
pst1.setString(4, day1.getText()+"/"+month1.getText()+"/"+year1.getText());
pst1.setString(5, day2.getText()+"/"+month2.getText()+"/"+year2.getText());
pst1.setString(6, engineerName.getText());
pst2.setInt(1, uniqueID);
pst2.setString(2, engineerName.getText());
pst2.setString(3, engineerPassword.getText());
try{
for (int j = 0; j < table.getRowCount(); j++ ){
pst3.setInt(1, uniqueID);
pst3.setString(2, table.getValueAt(j, 0).toString());
pst3.setString(3, table.getValueAt(j, 1).toString());
pst3.setString(4, table.getValueAt(j, 2).toString());
pst3.setString(5, table.getValueAt(j, 3).toString());
pst3.setString(6, table.getValueAt(j, 4).toString());
pst3.setString(7, table.getValueAt(j, 5).toString());
pst3.setDouble(8, 0.0);
pst3.execute();
}}catch(Exception e3){
/*JOptionPane.showMessageDialog(null, e3);
*
*/
}
pst4.setInt(1, uniqueID);
pst4.setString(2, null);
pst1.execute();
pst2.execute();
pst4.execute();
System.out.println(pst1.toString());
System.out.println(pst2.toString());
pst1.close();
pst2.close();
pst3.close();
pst4.close();
conn.close();
}
You should leave out auto generated column "uniqueID" and rewrite your code.
Ex.
String query4 = "insert into ProjectImages (Path) values(?)";
Another approach - passing null value for auto generated column. Ex.
String query4 = "insert into ProjectImages (uniqueId, Path) values(null,?)";
Without the stack trace it might be difficult to get where this is not working. It might be a INDEX constraint exception, a null pointer exception, ... But, I'd suggest to format differently the date, instead of
day1.getText()+"/"+month1.getText()+"/"+year1.getText()
I'd use
year1.getText()+"-"+month1.getText()+"-"+day1.getText()
(check the MySQL documentation and especially the STR_TO_DATE() function, but you probably don't need it).
And also there's room to improve your code (following Rajesh's comment):
While probably you're using Java 7 or above, I'd add the try-with statement for the connection;
Catching Exception is generally bad practice, I'd go for a fine-grain try-catch with SQLException, ...
I can't see any transaction strategy in place. I'd be worried while some of the pst?.execute() works fine and another doesn't, leaving your database in an inconsistent state.

Categories