Receiving all columns with StringBuilder - java

I've written a method that performs the following commands: select, insert, update, delete. Originally, I only wanted the first two columns of output after running SELECT * FROM SithLords. How can I get all of the rows and columns? Also, how can I allow the user to add newlines when running the select command like this:
SELECT jedi_name
FROM SithLords
WHERE level = 'master';
As of now, it only executes with one line:
select jedi_name from SithLords where level = 'master';
Code:
public void actionPerformed(ActionEvent e) {
String query = queryStatements.getText();
try {
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(query);
if(query.matches("(select|SELECT).*")) {
ResultSet result = stmt.executeQuery();
StringBuilder strResult = new StringBuilder();
while(result.next()) {
strResult.append(result.getString(1)).append(" ").append(result.getString(2));
strResult.append("\n");
}
queryResults.setText(strResult.toString());
} else if(query.matches("(insert|INSERT).*")) {
stmt.executeUpdate(query);
} else if(query.matches("(update|UPDATE).*")) {
stmt.executeUpdate(query);
} else if(query.matches("(delete|DELETE).*")) {
stmt.executeUpdate(query);
} else {
System.out.println("Not supported yet!");
}
} catch (SQLException error) {
error.printStackTrace();
}
}

If what you want is to retrieve from the recorset all its columns you could ask it how many columns does it have (n) and access from 1 to n:
ResultSet result = stmt.executeQuery();
ResultSetMetaData md = result.getMetaData();
int nCols = md.getColumnCount();
for(int c = 1; c <= nCols; c++)
strResult.append(result.getString(c).append(" "));
Concerning your multiline commands, you could replace the command end of lines by spaces:
query.replaceAll("(\\r|\\n)", " ");

Related

java - jTable database repeating values

I am trying to populate a java database with car brands, models, and if they are available but I have a big issue. When I enter multiple cars to the table, the new car prints to the table, but previous cars I have entered also reprint
[Issue.png][1]. So first I entered Ferrari Enzo, then I entered Tesla S but Ferrari Enzo is repeating.
I know the issue is not with adding the cars to the database because if I look in the database it only shows the two I entered [DatabasePic.png][2]. I know my problem is with how I am entering my cars into the JTable. My methods are below..
ButtonClickEvent:
private void refreshbtnMouseClicked(java.awt.event.MouseEvent evt) {
try {
String Brand = brandlbl.getText();
String Model = modellbl.getText();
Boolean Available = false;
switch (availabilitybox.getSelectedItem().toString()) {
case "True":
Available = true;
break;
case "False":
Available = false;
break;
}
InsertApp nw = new InsertApp();
nw.insert(Brand, Model, Available);
nw.refreshDatabase(jTable1);
} catch (SQLException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
Insert Method:
public void insert(String brand, String model, Boolean available) {
String sql = "INSERT INTO CARDATA(brand,model,available) VALUES(?,?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, brand);
pstmt.setString(2, model);
pstmt.setBoolean(3, available);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
Refreshing my database:
public void refreshDatabase(JTable table) throws SQLException {
Connection con = connect();
String SQL = "SELECT * FROM CARDATA";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
int col = rs.getMetaData().getColumnCount();
System.out.println(col);
while (rs.next()) {
Object[] rows = new Object[col];
for (int i = 1; i <= col; i++) {
rows[i - 1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, rows);
}
con.close();
rs.close();
stmt.close();
}
When I enter multiple cars to the table, the new car prints to the table, but previous cars I have entered also reprint
You need to clear the data in the TableModel before you start adding data back into it.
The basic code should be something like:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.setRowCount(0);
while (rs.next())
{
...
model.addRow(...);
}
Or instead of retrieving all the data from the database every time you do an insert, just add the data to the table at the same time:
pstmt.executeUpdate();
model.addRow(...);

Failed insert in mysql database jdbc from Java [duplicate]

I want to insert multiple rows into a MySQL table at once using Java. The number of rows is dynamic. In the past I was doing...
for (String element : array) {
myStatement.setString(1, element[0]);
myStatement.setString(2, element[1]);
myStatement.executeUpdate();
}
I'd like to optimize this to use the MySQL-supported syntax:
INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]
but with a PreparedStatement I don't know of any way to do this since I don't know beforehand how many elements array will contain. If it's not possible with a PreparedStatement, how else can I do it (and still escape the values in the array)?
You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().
Here's a kickoff example:
public void save(List<Entity> entities) throws SQLException {
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (Entity entity : entities) {
statement.setString(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.
See also:
JDBC tutorial - Using PreparedStatement
JDBC tutorial - Using Statement Objects for Batch Updates
When MySQL driver is used you have to set connection param rewriteBatchedStatements to true ( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**).
With this param the statement is rewritten to bulk insert when table is locked only once and indexes are updated only once. So it is much faster.
Without this param only advantage is cleaner source code.
If you can create your sql statement dynamically you can do following workaround:
String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" }, { "3-1", "3-2" } };
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
myStatement.executeUpdate();
In case you have auto increment in the table and need to access it.. you can use the following approach... Do test before using because getGeneratedKeys() in Statement because it depends on driver used. The below code is tested on Maria DB 10.0.12 and Maria JDBC driver 1.2
Remember that increasing batch size improves performance only to a certain extent... for my setup increasing batch size above 500 was actually degrading the performance.
public Connection getConnection(boolean autoCommit) throws SQLException {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(autoCommit);
return conn;
}
private void testBatchInsert(int count, int maxBatchSize) {
String querySql = "insert into batch_test(keyword) values(?)";
try {
Connection connection = getConnection(false);
PreparedStatement pstmt = null;
ResultSet rs = null;
boolean success = true;
int[] executeResult = null;
try {
pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < count; i++) {
pstmt.setString(1, UUID.randomUUID().toString());
pstmt.addBatch();
if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
executeResult = pstmt.executeBatch();
}
}
ResultSet ids = pstmt.getGeneratedKeys();
for (int i = 0; i < executeResult.length; i++) {
ids.next();
if (executeResult[i] == 1) {
System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
+ ids.getLong(1));
}
}
} catch (Exception e) {
e.printStackTrace();
success = false;
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
if (success) {
connection.commit();
} else {
connection.rollback();
}
connection.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
This might be helpful in your case of passing array to PreparedStatement.
Store the required values to an array and pass it to a function to insert the same.
String sql= "INSERT INTO table (col1,col2) VALUES (?,?)";
String array[][] = new String [10][2];
for(int i=0;i<array.size();i++){
//Assigning the values in individual rows.
array[i][0] = "sampleData1";
array[i][1] = "sampleData2";
}
try{
DBConnectionPrepared dbcp = new DBConnectionPrepared();
if(dbcp.putBatchData(sqlSaveAlias,array)==1){
System.out.println("Success");
}else{
System.out.println("Failed");
}
}catch(Exception e){
e.printStackTrace();
}
putBatchData(sql,2D_Array)
public int[] putBatchData(String sql,String args[][]){
int status[];
try {
PreparedStatement stmt=con.prepareStatement(sql);
for(int i=0;i<args.length;i++){
for(int j=0;j<args[i].length;j++){
stmt.setString(j+1, args[i][j]);
}
stmt.addBatch();
stmt.executeBatch();
stmt.clearParameters();
}
status= stmt.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
It is possible to submit multiple updates in JDBC.
We can use Statement, PreparedStatement, and CallableStatement objects for batch update with disabled auto-commit.
addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate.
Here addBatch() method adds a set of statements or parameters to the current batch.

Inserting information from one mysql table to another

I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;

Correct way to find rowcount in Java JDBC

I have tried different ways to get the row count in java JDBC, nut none seemed to be giving the correct result. Is there anything wrong that I am doing ?
Even though the customer table is empty and I should be getting the rowcount as 0, I don't understand why I get a non zero rowcount value.
Method 1 -
query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
rowcount = metaData.getColumnCount();
Method 2 -
query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
rowcount = rs.last() ? rs.getRow() : 0;
See this snippet of code:
import java.io.*;
import java.sql.*;
public class CountRows{
public static void main(String[] args) {
System.out.println("Count number of rows in a specific table!");
Connection con = null;
int count = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try {
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter table name:");
String table = bf.readLine();
ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);
while (res.next()){
count = res.getInt(1);
}
System.out.println("Number of row:"+count);
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
This the way I use to get the row count in Java:
String query = "SELECT * FROM yourtable";
Statement st = sql.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet rs = st.executeQuery(query);
int rows = 0;
rs.last();
rows = rs.getRow();
rs.beforeFirst();
System.out.println("Your query have " + rows + " rows.");
When you working with JDBC that does not support TYPE_FORWARD_ONLY use this method to get rowcount.
Statement s = cd.createStatement();
ResultSet r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM TableName");
r.next();
int count = r.getInt("rowcount");
r.close();
System.out.println("MyTable has " + count + " row(s).");
You can Get Row count using above method.
Thanks..
In Android, having no results returns an error. So check this case before incrementing count in while(resultset.next())
if(resultset!=null)
{
//proceed with incrementing row count function
}
else
{
// No resultset found
}
Just iterate and count
ResultSet result = sta.executeQuery("SELECT * from A3");
int k=0;
while(result.next())
k++;
System.out.print(k); //k is the no of row
As method name specifies metaData.getColumnCount() will return total number of columns in result set but not total no of rows (count).

Java: Insert multiple rows into MySQL with PreparedStatement

I want to insert multiple rows into a MySQL table at once using Java. The number of rows is dynamic. In the past I was doing...
for (String element : array) {
myStatement.setString(1, element[0]);
myStatement.setString(2, element[1]);
myStatement.executeUpdate();
}
I'd like to optimize this to use the MySQL-supported syntax:
INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]
but with a PreparedStatement I don't know of any way to do this since I don't know beforehand how many elements array will contain. If it's not possible with a PreparedStatement, how else can I do it (and still escape the values in the array)?
You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().
Here's a kickoff example:
public void save(List<Entity> entities) throws SQLException {
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (Entity entity : entities) {
statement.setString(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.
See also:
JDBC tutorial - Using PreparedStatement
JDBC tutorial - Using Statement Objects for Batch Updates
When MySQL driver is used you have to set connection param rewriteBatchedStatements to true ( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**).
With this param the statement is rewritten to bulk insert when table is locked only once and indexes are updated only once. So it is much faster.
Without this param only advantage is cleaner source code.
If you can create your sql statement dynamically you can do following workaround:
String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" }, { "3-1", "3-2" } };
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
myStatement.executeUpdate();
In case you have auto increment in the table and need to access it.. you can use the following approach... Do test before using because getGeneratedKeys() in Statement because it depends on driver used. The below code is tested on Maria DB 10.0.12 and Maria JDBC driver 1.2
Remember that increasing batch size improves performance only to a certain extent... for my setup increasing batch size above 500 was actually degrading the performance.
public Connection getConnection(boolean autoCommit) throws SQLException {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(autoCommit);
return conn;
}
private void testBatchInsert(int count, int maxBatchSize) {
String querySql = "insert into batch_test(keyword) values(?)";
try {
Connection connection = getConnection(false);
PreparedStatement pstmt = null;
ResultSet rs = null;
boolean success = true;
int[] executeResult = null;
try {
pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < count; i++) {
pstmt.setString(1, UUID.randomUUID().toString());
pstmt.addBatch();
if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
executeResult = pstmt.executeBatch();
}
}
ResultSet ids = pstmt.getGeneratedKeys();
for (int i = 0; i < executeResult.length; i++) {
ids.next();
if (executeResult[i] == 1) {
System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
+ ids.getLong(1));
}
}
} catch (Exception e) {
e.printStackTrace();
success = false;
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
if (success) {
connection.commit();
} else {
connection.rollback();
}
connection.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
This might be helpful in your case of passing array to PreparedStatement.
Store the required values to an array and pass it to a function to insert the same.
String sql= "INSERT INTO table (col1,col2) VALUES (?,?)";
String array[][] = new String [10][2];
for(int i=0;i<array.size();i++){
//Assigning the values in individual rows.
array[i][0] = "sampleData1";
array[i][1] = "sampleData2";
}
try{
DBConnectionPrepared dbcp = new DBConnectionPrepared();
if(dbcp.putBatchData(sqlSaveAlias,array)==1){
System.out.println("Success");
}else{
System.out.println("Failed");
}
}catch(Exception e){
e.printStackTrace();
}
putBatchData(sql,2D_Array)
public int[] putBatchData(String sql,String args[][]){
int status[];
try {
PreparedStatement stmt=con.prepareStatement(sql);
for(int i=0;i<args.length;i++){
for(int j=0;j<args[i].length;j++){
stmt.setString(j+1, args[i][j]);
}
stmt.addBatch();
stmt.executeBatch();
stmt.clearParameters();
}
status= stmt.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
It is possible to submit multiple updates in JDBC.
We can use Statement, PreparedStatement, and CallableStatement objects for batch update with disabled auto-commit.
addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate.
Here addBatch() method adds a set of statements or parameters to the current batch.

Categories

Resources