i need a help when i execute the following MYSQL command in Navicat i get
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
when i fire it in java i get
java.sql.SQLException: Column Index out of range, 3 > 2.
Code :-
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
Since you are only getting 1 column, you are out of range. You change your code as follows, and remove your counter.
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
while(rs.next())
{
A.add(rs.getString("Password"));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
You have 5 entries in your database table and execute the following code:
int c = 1;
while (rs.next()) {
A.add(rs.getString(c)); // get value at column
c++;
}
1st iteration: rs.getString(1), get value at column 1
2nd iteration: rs.getString(2), get value at column 2
and so on
Now, your table only has one column, therefore you should access your value with either
rs.getString(int column), here always 1
rs.getString(String columnLabel), here Password
Related
I have a MySQL db and I have an issue with two tables named product and product_older. They have same structure and product table's rows copied into product_older for once in a day. Here is their structure:
+-----------------------+---------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+---------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| price | decimal(18,2) | YES | | NULL | |
| price_older | decimal(18,2) | YES | | NULL | |
+-----------------------+---------------+------+-----+-------------------+----------------+
I have problem with only price_older field. My program updates values of product table for over 3 million data. price_older field takes it value from price column of product_older every time.
Here is the method which I take price_older:
private double getOlderPrice(int id) {
double price_older = 0.0d;
try {
String query = tools.getQuery("select price from product_older where id=?")
.replace("?", String.valueOf(id));
com.mysql.jdbc.Connection connection = (Connection) DriverManager.getConnection(db_url, username, password);
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
price_older = resultSet.getDouble(1);
}
} catch (SQLException e) {
..... // error log
} finally {
.... //close the prepared statement
}
return price_older;
}
And I use that price_older value to create PriceList object for every product then I used that list to update product table. Here is my update code:
(Same connection object used in here with the getOlderPrice method.)
private void dbUpdate() throws SQLException {
String query = "update product set price=?, price_older=? where id=?";
try (com.mysql.jdbc.Statement statement = (Statement) connection.createStatement();
com.mysql.jdbc.PreparedStatement updateStatement = (PreparedStatement) connection.prepareStatement(query)) {
connection.setAutoCommit(false);
int batchIndex = 0;
for (UpdatePrice price : priceList) {
if (price.getPrice() == null) {
updateStatement.setNull(1, Types.DECIMAL);
} else {
updateStatement.setDouble(1, price.getPrice());
}
updateStatement.setDouble(2, price.getOlderPrice());
updateStatement.setInt(3, price.getID());
updateStatement.addBatch();
batchIndex++;
if (batchIndex % limitedBatchSize == 0) {
updateStatement.executeBatch();
connection.commit();
}
}
updateStatement.executeBatch();
connection.commit();
connection.setAutoCommit(true);
priceList.clear();
}
}
Here is the problem; It works fine for most of the time but about once every ~30 days it updates older_price with the wrong value and that wrong value is usually belong to another product in the db and when it updates the column with the wrong value there is no error in the log because it appears OK.
And my connection's rewriteBatchedStatements is set to true.
How could that be? If there is a bug, why it works fine most of the time and how there is no problem with the price column? If there is not why it updates a value in the wrong place?
I have been searched for over a week now but there is no result and also I can not reproduce the bug and it makes less possible to be sure where is the problem actually.
a table has a column named 'score' with different values.
| name | contact | area | score |
| james | +222451 | eastp|70 |
| jimmy | +222451 | eestp | 80 |
| k.josh | +222451 | ecstp | 50 |
| L.john | +222451 | efstp | 60 |
I want to update all score values with a specific value. eg. update all score values with 10.
therefore value 70 will be 80
value 80 will be 90
value 50 will be 60
value 60 will be 70
please how do I write a code to achieve this. wrote down this but all columns get changed to the same value. please help.
int reg = 10;
try {
String sql1 = "select Score from db_table where ID=db_table.ID";
pst = con.prepareStatement(sql1);
rs = pst.executeQuery();
while(rs.next())
{
int ad = rs.getInteger("Score");
int fad = ad+reg;
String sql2 = "update db_table set Score='" + fad + "' where _ID=db_table.ID";
pst = con.prepareStatement(sql2);
pst.execute();
}
} catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null,e);
} finally
{
try
{
rs.close();
pst.close();
} catch(Exception e)
{}
}
but anytime is executed, the whole column values are replaced with the same value '10'. instead of each column value should rather be increased by 10. please help
Use the following query:
UPDATE db_table
SET score = score + 10
So, basically you don't need to SELECT all the scores first, and then manipulate them inside Java code, and use UPDATE one by one. Instead, change your try block in the Java code as follows:
try
{
String sql1 = "UPDATE db_table Set score = score + " + String.valueOf(reg);
pst = con.prepareStatement(sql1);
rs = pst.executeQuery();
}
Try this:
int reg = 10;
try{
String sql1="select Score from db_table where ID=db_table.ID";
pst=con.prepareStatement(sql1);
rs=pst.executeQuery();
while(rs.next()){
int ad = rs.getInteger("Score");
int fad = ad+reg;
String sql2 = "update db_table set Score=Score + "+fad+" where _ID=db_table.ID";
pst=con.prepareStatement(sql2);
pst.execute();
}
}catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null,e);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){}
}
2 problems, it outputs 1 2 3 4 3 5, instead of 1 2 3 4 5, which I'm not sure why followed by success but does not print out the data from the SQL table
Statement st = null;
ResultSet rs = null;
try {
System.out.println("1");
Connection con = DriverManager.getConnection(url, user, pass);
System.out.println("2");
//Class.forName(driver);
System.out.println("3");
st = con.createStatement();
rs = st.executeQuery("SELECT productcost " +
"FROM producttable " +
"WHERE productid = 3;");
System.out.println("4");
if (rs.next()) { //get first result
System.out.println(rs.getInt(1)); //coloumn 1
}
System.out.println("5");
System.out.println("Success");
} catch (Exception e) {
System.out.println("Error");
}
The reason you are seeing 3 in-between 4 and 5 is because the ResultSet contains 3.
ResultSet.getInt
Retrieves the value of the designated column in the current row of
this ResultSet object as an int
Try debugging your code and stepping through that section. You'll see what I am displaying below.
You must have '3' as a data in first column! Cause your printing the data of first column of record.i don't see any problem here!
I am using MySQL 5.1 for my database and I'm sending the commands via a Java program (JBDC).
Is there a MySQL command for creating or altering a table?
Let's say I have a following table:
+----------+----------+
| column_a | column_b |
+----------+----------+
| value_a | value_b |
+----------+----------+
Now I want to use a command, that would add a column "column_c" if it didn't exist.
That would result in:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
| value_a | value_b | |
+----------+----------+----------+
If the table didn't exist, it would create a new table with specified columns:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
And finally, if the table had columns that weren't specified in the command, it would leave them untouched.
here is code in Java to create a table called Coffees:
/*Making the connection*/
try {//if any statements within the try block cause problems, rather than the program failing
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection(url, "your username", "your password");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("create table COFFEES (COF_NAME varchar(32), " +
"SUP_ID int, PRICE double, SALES int, TOTAL int, " +
"primary key(COF_NAME))");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Explanation:
-In this example the java program interacts with a database that is located on a server, so we have to firstly we set the url of where the server is located and also sign in username and password, you may not be using the same method that I used.
-These need to be declared at the top of your java program:
String url = "jdbc:mysql://www.yoururlexample.co.uk";
Connection con;
Statement stmt
Hopefully this helps, you will then be able to insert data into the database and execute queries.
Edit:
This can be used in the executeUpdate statement if you want a table to be created if none exists with the name "COFFEES":
create table if not exists COFFEES
/*Making the connection*/
try {
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection("jdbc:mysql:exaple.com", "username", "pass");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("ALTER TABLE table_name ADD column_name datatype");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
I think that this is going to work for you.
Something like that might be a solution (this need at least one record in the table to work):
package com.stackoverflow.so20935793;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class App {
// complete this:
private static final String JDBC_URL = ".....";
private static final String JDBC_USER = ".....";
private static final String JDBC_PASS = ".....";
public static void main(final String[] args) {
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
stm = con.prepareStatement("SELECT * FROM your_table LIMIT 1");
rs = stm.executeQuery();
if (rs.next() && rs.getMetaData().getColumnCount() == 2) {
// add your new column
}
} catch (final SQLException ex) {
// handle exception
} finally {
closeQuietly(rs);
closeQuietly(stm);
closeQuietly(con);
}
}
private static void closeQuietly(final AutoCloseable what) {
if (what == null) {
return;
}
try {
what.close();
} catch (final Exception ex) {
// ignore
}
}
}
(not tested)
I want to fetch a table from a database using Java code. The sample code which I tried gets only two columns. I want the fetched data to be presented exactly like it is in the table.
How do I do that ?
This code only gives me two rows, side by side -
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
Full example at -
http://msdn.microsoft.com/en-us/library/aa342339.aspx
This is what I tried -
int size = 0;
if(rs != null){
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
System.out.println("cols = " + size);
And got an error - The requested operation is not supported on forward only result sets.
Use this code
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
Source - How to get the number of columns from a JDBC ResultSet?
After using that code, one can display the results like they are displayed by the DBMS as follows -
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
// Iterate through the data in the result set and display it.
while (rs.next()) {
//Print one row
for(int i = 1 ; i <= columnsNumber; i++){
System.out.print(rs.getString(i) + " "); //Print one element of a row
}
System.out.println();//Move to the next line to print the next row.
}
Column names are not displayed in this example.
I posted this answer to a similar question here, but I believe this one is also relevant, maybe more so. In short, I wrote a simple utility class to print db table rows to standard out (for part fun, part learning). It may be useful to someone (at least I hope so).
Here is the link to the code repo at GitHub: https://github.com/htorun/dbtableprinter
And here is the basic usage:
// Create a connection to the database
Connection conn = DriverManager.getConnection(url, username, password);
// Just pass the connection and the table name to printTable()
DBTablePrinter.printTable(conn, "employees");
It should print something like this:
Printing 10 rows from table(s) EMPLOYEES
+--------+------------+------------+-----------+--------+-------------+
| EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME | GENDER | HIRE_DATE |
+--------+------------+------------+-----------+--------+-------------+
| 10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 |
+--------+------------+------------+-----------+--------+-------------+
| 10002 | 1964-06-02 | Bezalel | Simmel | F | 1985-11-21 |
+--------+------------+------------+-----------+--------+-------------+
.
.
It's because your code only get 2 value of the row. Notice that rs.getString(4) meant, get the value on current row at 4th column (using 0 based index) as String.
If you want to print all the column, you should write the rest rs.getXXXX(), where XXXX is column data type such as getString(), getInteger(), getLong(), etc. See this java documentation for reference.
public static void printSqlTable(String selectQuery) {
try {
Statement statement = connection.createStatement();
resultSet = statement.executeQuery(selectQuery);
DBTablePrinter.printResultSet(resultSet);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}