I am trying to create a table with values that are in a String array. I am looking for the best way to loop through it without having to send a bunch of queries. This is what I have but obviously the loop wont work. Anyone have a better way of performing this?
public static void createTable(String table, String[] values) throws SQLException{
try {
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
Statement state = conn.createStatement();
for(int x = 0; x < values.length; x++){
state.execute("CREATE TABLE" + table + " ( " + values[x] + " );");
}
conn.commit();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Concatenate the elements of Values array.
StringBuilder sb=new StringBuilder();
sb.append("CREATE TABLE " + table + " ( ");
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i >= values.length-1) {break;}
sb.append(",");
}
sb.append(" )");
state.execute(sb.toString());
Related
I have a form that has a ComboBox which it gets its items from a database. The combobox takes numerous column-items from a table inside the database.
I want to take only one of these items (from the combobox) and copy it to a JTextField.
Here's the code of the creation of the ComboBox in the Order.java file:
cbinv = new JComboBox<>();
cbinv.setModel(new InvComboModel(con));
and the code from the InvComboModel.java:
public InvComboModel(Connection con) {
try {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "SELECT * FROM inventory";
rs = stmt.executeQuery(query);
} catch (SQLException e) {
System.out.println("InvComboModel: " + e.getMessage());
}
}
#Override
public String getElementAt(int index) {
String lstn = null;
try {
rs.absolute(index + 1);
lstn = rs.getString("category") + ", " + rs.getString("description") + ", "
+ rs.getInt("price") + ", " + rs.getInt("quantity");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return lstn;
}
#Override
public int getSize() {
int cnt = 0;
try {
rs.last();
cnt = rs.getRow();
} catch (SQLException ex) {
System.out.println("getSize(): " + ex.getMessage());
}
return cnt;
}
public int getIdInvAt(int index) {
int idInv = 0;
try {
rs.absolute(index + 1);
idInv = rs.getInt("idinv");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return idInv;
}
So, I want when I select something on the Inventory Item to take the third value (which in this case is 500, example image) and copy it to the JTextField of the ItemPrice.
[example][1]: https://i.stack.imgur.com/BWQVw.jpg
In the Order.java file I have the following command but it copies all the selected item in the combobox:
tip.setText((String) cbinv.getSelectedItem());
and when I use the following command it takes the whole line again. It seems that I can't use any other method from the InvComboModel.java file
tip.setText((String) cbinv.getModel().getElementAt());
Thanks in advance.
I want to be able to sort a table from the database, according to either the quatity or the name, but how do i decided what happens in what case?
Below is the code for the table.
public void tableupdate(JTable jTable1, String fill) {
try {
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:D:/Inventory.db", "sa", "");
Statement stat = con.createStatement();
fill = "SELECT * FROM BOOKDESC ";
ResultSet rs = stat.executeQuery(fill);
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
MySQL is offering a method for sorting data in your SELECT statement, it's called ORDER BY.
Usage is found here.
This way, your code doesn't have to do the work, as your ResultSet already gets sorted data.
I have the following codes snippet. I remove further details. I have a for loop with all the data in it. The I run the for loop for (int i = 0; i < list.getLength(); i++). What happens is that the moment any one of the data cause the sql with error say the data has a slash etc then it cause exception and the rest of the for loop cant continue. How can I like skip the one with the exception and continue with rest?
Here is a the codes.
Connection dbconn = null;
Statement stmt1 = null;
Statement stmt2 = null;
try
{
dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "tes1", "te15");
stmt1 = dbconn.createStatement();
stmt2 = dbconn.createStatement();
DateFormat outDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = Calendar.getInstance().getTime();
String value = null;
for (int i = 0; i < list.getLength(); i++)
{
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
}
}
catch (SQLException ex)
{
System.out.println("MyError Error SQL Exception : " + ex.toString());
}
catch (Exception rollback)
{
System.out.println("\nRollback :");
rollback.printStackTrace(System.out);
}
catch (Exception e)
{
System.out.println("\n Error here :");
e.printStackTrace(System.out);
}
finally
{
try
{
if (stmt1 != null)
{
stmt1.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt1 close");
ex.printStackTrace(System.out);
}
try
{
if (stmt2 != null)
{
stmt2.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt2 close");
ex.printStackTrace(System.out);
}
try
{
if (dbconn != null)
{
dbconn.close();
}
else
{
System.out.println("MyError: dbConn is null in finally close");
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for dbConn close");
ex.printStackTrace();
}
}
You need to put the try/catch block inside the for, around executeUpdate(insertCommand);
You need to catch the error in the loop too
....
for (int i = 0; i < list.getLength(); i++) {
try {
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
} catch (Exception e) {
// Better catch the real exception
// Handle the exception
}
}
....
I have a result set ResultSet rs=stmt.executeQuery(); I wrote a method to print query results as following
public void printResults(ResultSet rs) {
// Getting column names
int j = 1;
while (true) {
try {
System.out.print(rs.getMetaData().getColumnName(j)+" ");
j++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
// Getting results
while(rs.next()) {
int i = 1;
while (true) {
try {
System.out.print(rs.getString(i)+" ");
i++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
}
}
My issue is : is it a good idea to use try && catch ... I feel that it is not? Does it impact speed? What is a better way?
Thank You
You can get column number by
ResultSetMetaData meta= rs.getMetaData();
int columnNum=meta.getColumnCount();
Loop with this columnNum to get the result as well as column name.
for(int i=1;i<=columnNum;i++){
System.out.print(meta.getColumnName(i)+" ");
}
//Get the data
while(rs.next){
for(int i=1;i<=columnNum;i++){
System.out.print(rs.getString(i)+" ");
}
}
preparedbatch method takes resultset of size 1000.
I am inserting data using prepared statement and batch.
Using LIMIT I am pulling 1000 rows from mysql database, java.. and calculating some value from column values of each row..
public class Method {
void preparedBatch (ResultSet rs, PreparedStatement insert) throws Exception{
int y;
int arr[]= new int[40];
while (rs.next()){
for(y=2;y<=41;y++){
arr[y-2]=rs.getInt(y);
}
insert.setString(1, rs.getString(1));
insert.setLong(2, calculate(arr));
insert.addBatch();
}
{
insert.executeBatch();
insert.clearBatch(); // I did this to avoid oOM
}
rs.close(); //if I do not close, then I get OOM error
}
long calculate (int[] arr){
long sum =0;
for(int k=0;k<40;k++){
sum+= arr[k]*pow(2,k);
}
return sum;
}
long pow(long base, int exponent)
{
if (exponent == 0)
return 1; // base case;
double temp = pow(base, exponent/2);
if (exponent % 2 == 0)
return (long) (temp * temp);
else
return (long) (base * temp * temp);
}
void method(){
Method k = Insert.m1;
System.out.println("in metho");
Database d1= new Database(); // for reading from tables
d1.setPassword("abc");
d1.setUrl("jdbc:mysql://localhost/DB");
d1.setUser("root");
// object to calculate 2 raise to 39 stuff
ResultSet rs =null;// result set for 2500 lines selected
PreparedStatement ps=null,insert=null; //ps for selecting 1000 lines //insert for inserting into binary table
final Connection con;
try {
con = DriverManager.getConnection(d1.getUrl(), d1.getUser(), d1.getPassword());
con.setAutoCommit(false);
insert = con.prepareStatement("insert into binarydata values(?,?)");
int z;
for(z=0;z<=850000;z=z+1000)
{
ps = con.prepareStatement("select * from table1 LIMIT "+z +", 1000");
rs= ps.executeQuery();
try {
k.preparedBatch(rs,insert);//k is global object of Methodclass
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs.close();
if(z%200000==0){
System.out.println(z +" inserted this time");
}
if(z==850000){
System.out.println(z +"mouse");
}
}
{
ps = con.prepareStatement("select * from table1 LIMIT 851000 , 364");
insert = con.prepareStatement("insert into binarydata values(?,?)");
rs= ps.executeQuery();
try {
k.preparedBatch(rs,insert);
System.out.println("finally inserting");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(rs.getString(1));
}
rs.close();
}
try {
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
con.close();
ps.close();
insert.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My main class creates object of Method and invokes method from it,
my array is 0,1,0,1,1,1,1,1,,0,0,0,0,0,0,0,1,0 ( it is an example, all 851364 rows contain such data)
if my arr for example is 0,1,0, then I am calculating sum+= arr[index]*2 (power index).. like this..
I have no knowledge of Springs, otherwise I would have used that to handle data of my size.
Please help me understand, why in method preparedBatch, I have to close resultset?
Also, please suggest optimized code of this.
It took me some 9 minutes, to read 85136 lines and insert respective sum..