I can only get results from a SQL query execution when I use select columnname from tablename, but not when I use select * from tablename
public static void connectAndExecute(String host, String uName, String uPass, String sqlQuery) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
} catch (SQLException e) {
e.printStackTrace();
}
try {
Connection con=DriverManager.getConnection(host, uName, uPass);
String[] conData = null;
Statement stmt = null;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
/*this is the place of my problem*/
}
catch (SQLException e) {
e.printStackTrace();
}
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
}
Use ResultSet.class methods to get the desired result. You can give the column names or column index.
getInt(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as an int in the Java programming language.
getString(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a String in the Java programming language.
Here is how you can implement it:
while(rs.next()){
//Retrieve by column index
int id = rs.getInt(1); //assume id is at 1st index
int age = rs.getInt(4); //assume age is at 4th index
String first = rs.getString(2); // assume first name is at 2nd index
String last = rs.getString(3); // assume last name is at 3rd index
//Display values
System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last);
System.out.println(" End of one row");
}
Related
i'm a new programmer, I was given a task to create a class Subject.java, in which it'll ask the students how many subjects they're taking and then store the subjects information into the database, but the problem with my current code is that only one row is updated in the database. My code is as the following, please help me.
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i=0;
for (i=0; i<sub; i++)
{
System.out.print("\nCode: ");
this.setCode(in.next());
System.out.print("\nName: ");
this.setName(in.next());
System.out.print("\nCredit: ");
this.setCredit(in.nextInt());
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
try (Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);)
{
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt (3, this.getCredit());
pstmt.addBatch();
if (pstmt.executeUpdate() == 1)
{
System.out.println("\nNew subject has been created succesfully!");
}
else
{
System.out.println("\nError");
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
As Nexevis said , you need to put your Connection code outside your for-loop like below :
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i = 0;
try {
Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);
for (i = 0; i < sub; i++) {
System.out.print("\nCode: ");
this.setCode( in.next());
System.out.print("\nName: ");
this.setName( in.next());
System.out.print("\nCredit: ");
this.setCredit( in.nextInt());
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt(3, this.getCredit());
pstmt.addBatch();
}
try {
// execute it to insert the data
pstmt.executeBatch();
} catch (SQLException e) {
System.out.println("Error message: " + e.getMessage());
return; // Exit if there was an error
}
pstmt.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
I am trying to figure out a way to see if the sql injection is correct based on the user input and if so, delete that row.
For instance the user enters 123 for an idNumber, if that number exits, the the sql statement "select * from student where idNumber = " + idNumber + ";" would be correct.
When it is verified that it is correct, I would then use another statement to delete the query.
My main issue is figuring out how to verify it is correct.
Thanks!
public static void CheckStudent(Connection con, String idNumber) throws SQLException {
Statement stmt = null;
String query = "select * from student where idNumber = " + idNumber + ";"
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (!rs.isBeforeFirst() ) {
//Here is where you do the check
System.out.println("No data");
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
I'm working on shifts manager program which calculates monthly salary and etc.
the program based on SQLite database which keeps getting updated by the user input.
my question is , how can i use the SQLite function in java to retrieve information, lets say monthly salary in one command (i know i can use " select sum(tips) between date1 and date2",but how can i get the function result inside a variable?)
so far i've created a function which gets two dates and retrieves all the shifts salary between these dates and summarise them with ResultSet.
here's my code:
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select tips from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum += rs.getInt("tips");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}
I edited your code.
Note that in case you select the sum of the tips, the column name changes. You also get only one row with one column as your result, so you should not need the while loop anymore.
The sum of the tips is now saved in the variable sum
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select sum(tips) from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum = rs.getInt("sum(tips)");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}
Hi guys can u tell me what is wrong with my code?
When I set my ResultSet as "SELECT * FROM Table1" it works perfectly,
also if it is "SELECT key, itemName, itemPrice, itemQuantity FROM Table1"
but when I try to use only one of them or two it prints out an error column not found.
My database is stored in MS Acceess. That's my main:
try (Connection cn = DBUtil.getConnection(DBType.MS_ACCESS);
Statement st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT Table1.key FROM Table1");) {
Table1.displayData(rs);
} catch (SQLException ex) {
DBUtil.processException(ex);
}
and that's Table1.java:
public class Table1 {
public static void displayData(ResultSet rs) throws SQLException {
// to print out my database
while (rs.next()) {
StringBuffer buffer = new StringBuffer();
buffer.append(rs.getString("key") + " ");
buffer.append(rs.getString("itemName") + " ");
double price = rs.getDouble("itemPrice");
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
String formattedPrice = pounds.format(price);
buffer.append(formattedPrice + " ");
buffer.append(rs.getInt("itemQuantity") + " ");
System.out.println(buffer.toString());
}
}
}
Your result set will only contain the columns that you define in your select query. So if you do
rs.getString("itemName")
then you have to select that column in your query, which you don't
st.executeQuery("SELECT Table1.key FROM Table1")
^-----------------column missing
Do
st.executeQuery("select key, itemName, itemPrice, itemQuantity from Table1")
you should use
buffer.append(rs.getString("Table1.key") + " ");
resultset have the data with name which you have given in select query.(key=Table1.key)
I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}