I am trying to fetch data from postgres database using where clause. It is returning null values. But running the same query in postgres worksheet, it is giving the datas.
And one more thing, I cannot able to use without double quotes(\"USER_INFO\"),while using without double quotes I am getting the error "column name does not exist".
But most of the online examples are without double quotes only.
Please help on this to resolve. Thanks in advance.
public class PostGreDB {
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:5432/";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
//Statement st = null;
try{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","postgres","XXXX#1904");
//STEP 4: Execute a query
System.out.println("Creating statement...");
//st = conn.createStatement();
String sql;
sql = "SELECT * FROM public." + "\"USER_INFO\" where \"USER_INFO\".\"EMAIL_ID\" = ?";
System.out.println(sql);
try(PreparedStatement pst= conn.prepareStatement(sql)){
pst.setString(1 , "cppandi33#gmail.com");
pst.executeQuery();
try(ResultSet rs = pst.getResultSet()){
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String first = rs.getString("USER_ID");
String last = rs.getString("USER_NAME");
String email = rs.getString("EMAIL_ID");
//Display values
System.out.print("User ID: " + first+"\n");
System.out.println("User Name: " + last+"\n");
System.out.println("Email: " + email);
}
rs.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//STEP 6: Clean-up environment
// st.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
}
When column contains "null" as data. It gives null only. Try to insert some data using insert query and after that we can try to fetch.
Related
I am using XAMPP->Mysql to create database and using Netbeans IDE 8.1 fro create java
My Code
//default package
//1st step
import java.sql.*;
public class DemoJDBC {
public static void main(String[] args) {
try{
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
rs.next();
String name = rs.getString("sname");
System.out.println(name);
//6th step
con.close();
}
catch (Exception e){
}
}
}
Why it didn't show output name ? It just show
"BUILD SUCCESSFUL (total time: 1 second)" in netbeans output
You need to loop through the ResultSet to get the tuples or rows. So while looping you retrieve whatever data or field you want to get. try:
public static void main(String[] args) {
try {
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
//6th step
con.close();
} catch (Exception e) {
}
}
NOTE if by default you did not change the password of the root user it is just the empty String (thus "" and not "0"). Other than that you know what you are doing.
Along with the correction of your code to loop through the ResultSet, you also need to correct your connection string as shown below:
Considering that your MySQL is running on the default MySQL port 3306 (which I see that you already are), the connection string needs to be updated.
Also saw that password for the user root is '0', is it really the password?
public static void main(String[] args) {
try {
String query = "SELECT * FROM Student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "0");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
con.close();
} catch (Exception e) {
}
}
Also ensure to have your MySQL Connector/J jar file to be present in your CLASSPATH to not to face any reference issues.
Hope that this helps!
I have one problem that in my java programme when i select some record from database,i need records which are not retrun by sql query from database.
suppose i have 5 record in my table and i give 8 record in where condition in my java programme so i need 3 record in ArrayList for that programme did not retrun any values..
My sample programme is as below:-
import java.sql.*;
import java.util.ArrayList;
public class database {
static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
static final String DB_URL = "jdbc:oracle:thin:#localhost:1521:orcl";
static final String USER = "asiftest";
static final String PASS = "asif";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
ArrayList ar =new ArrayList();
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT contractno FROM temp_survival where contractno in ('77777','11111','22222','33333','44444','55555','66666','77777','363636','25252')";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String first = rs.getString("contractno");
System.out.print("contractno: " + first);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
For the above programme i am getting values for '77777','11111','22222','33333','44444','55555','66666','77777' but for next 2 records '363636','25252' i am are not getting values because that is not available in database table so i need to add them in arraylist in above proramme. Please help me
Make a List for input contact numbers (which you are passing in where clause)
Make a List of contact numbers which you are getting in the query results
Use CollectionUtils.substract(list1, list2)
I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?
I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}
I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");