I'm trying to display a list of the names of people in the database from the terminal, but not sure about how I would go about this. Right now I'm using a prepared statement
public static void showNames() throws SQLException {
Statement stmt=null;
Connection conn=null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String selectTable="SELECT * FROM userInfo;";
stmt.execute(selectTable);
}
You're close.
Below code is not a complete answer, but hopefully enough to get you moving in the direction of obtaining a complete answer. The below code is basically the code you posted with some modifications.
public static void showNames() throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
String selectTable="SELECT * FROM userInfo;";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
rs = stmt.executeQuery(selectTable);
while (rs.next()) {
Object obj = rs.getObject("name of column in database table USERINFO");
System.out.println(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
You didn't post the structure of database table USERINFO, so replace name of column in database table with the actual column name.
By the way, there are many examples of how to do this on the Internet, for example Processing SQL Statements with JDBC.
Related
So i got this form that I'm using but I get that error whenever i submit, it says CONNECTION SUCCESSFUL but then it returns the error and never insert nor retrieves anything from the db. I checked the version of the sqlite and everything, can't figure it out.
public class databaseConnection {
public static Connection connection = null;
public static Connection getConnection() throws ClassNotFoundException {
try {
System.out.println("CONNECTING");
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:SoftwareDB.db");
System.out.println("CONNECTION SUCCESSFUL");
} catch (SQLException e) {
System.out.println("ERROR: Connection Failed!");
}
return connection;
}
public static void login(String username, String password, String login) throws ClassNotFoundException {
try {
System.out.println("INSERTING");
try (Statement stmt = getConnection().createStatement()) {
String sql = "INSERT INTO login (username, password) VALUES ('" + username + "', '" + password + "', '" + login + "');";
stmt.execute(sql);
}
getConnection().close();
System.out.println("INSERT SUCCESSFUL");
} catch (SQLException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ResultSet getLoginDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
ps.close();
getConnection().close();
}
return rs;
}
public static ResultSet getExistentDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
getConnection().close();
}
return rs;
}
}
private void loginBtnMouseClicked(java.awt.event.MouseEvent evt) {
if (username.getText().isEmpty() || password.getText().isEmpty()) {
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} else {
try {
databaseConnection.getLoginDetails("SELECT * FROM register WHERE email = '?' AND password = '?'");
String ts = new SimpleDateFormat("dd.MM.yyyy - HH.mm.ss").format(System.currentTimeMillis());
databaseConnection.login(username.getText(), password.getText(), ts);
JOptionPane.showMessageDialog(null, "Login succesful!");
new login().setVisible(true);
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} catch (HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Failed!");
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output
I believe you have forgotten an important thing: properly preparing your PreparedStatement and opening/closing connections correctly.
Would you try the following rewritten getLoginDetails() method and take inspiration from it for the other methods?
public static ResultSet getLoginDetails(String query, String email, String password) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (Connection conn = getConnection()) {
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1,email);
ps.SetString(2,password);
rs = ps.executeQuery();
// Do something with the ResultSet here or do not close the statement!
}
}
return rs; // should be something else! (as it could be already closed)
}
Then you certainly need to do something with the ResultSet! For example: check that the email/password combination exists in order to validate the login request.
Also, some important remarks and tips:
better check that the connection is valid after initialization using isValid(timeout)
think about a connection pool or at least some ways to reuse your connection(s)
eventually use existing tools (libraries like Apache) for your ORM (Object-Relation Mapping) and DAO (Database Access Object) layers. Actually, that's highly recommended.
closing a PreparedStatement will automatically close the associated ResultSet. Your code does not take that into account. Cf. https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html
Keep me posted!
I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)
I have these at start of my class;
private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;
Methods for example;
public int lastPlaceProgram(){
String query= "Select * from userprogram where laststayed = 1";
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
int programid = 0;
while(rs.next()){
programid = rs.getInt("programid");
}
return programid;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
or
public String programType(int programid){
String query = "Select * from programs where id = ?";
try {
preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1, programid);
ResultSet rs = preparedStatement.executeQuery();
String type = "";
while(rs.next()){
type = rs.getString("type");
}
return type;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
And constructor;
public Operations() {
String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
try {
con = DriverManager.getConnection(url);
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
}
}
I tried to add these finally block to after catch blocks of all my 30 methods;
finally{
try{
con.close();
} catch(Exception e){
}
}
But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.
Finally blocks didn't work for me, i closed them manually if i had that variable to close. I mean if i used ResultSet and PreparedStatement at a method then i made rs.close() and preparedstatement.close() just before catch or before return. If i just had Preparedstatement variable on the method then i just did preparedstatement.close() before catch block or before return.
What I did wrong? I tried to swap rs.close(), pstmt.close(), conn.close().
I created a PreparedStatement.
But I still can not display the contents of a database table. If I remove conn.close(), everything works! How close the connection and get an output on the jsp?
This is my code:
public ResultSet executeFetchQuery(String sql) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = Database.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(PhoneDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
return rs;
}
public ArrayList<Phone> getAllPhone() {
ArrayList<Phone> list = new ArrayList<>();
String sql = "SELECT * FROM phones.product;";
ResultSet rs = executeFetchQuery(sql);
try {
while (rs.next()) {
Phone phone = new Phone();
phone.setId(rs.getInt("id"));
phone.setName(rs.getString("name"));
phone.setPrice(rs.getInt("price"));
phone.setQuantity(rs.getInt("quantity"));
phone.setDescription(rs.getString("description"));
System.err.println(phone);
list.add(phone);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return list;
}
ResultSet rs = executeFetchQuery(sql);
The above statement closes everything.
Actually your code should be
DBConnection
Iterate through result set
Store the values/display the value directly(depends on your need)
Finally close the connection.
Which is the proper way to access the data from db.
The more common pattern for this kind of process is to maintain the connection and the statement outside the main query code. This is priomarily because connections would generally be allocated from a pool as they are expensive to create and preparing the same statement more than once is wasteful.
Something like this is most likely to work both efficiently and correctly.
static final Connection conn = Database.getConnection();
static final String sql = "SELECT * FROM phones.product;";
static final PreparedStatement pstmt = conn.prepareStatement(sql);
public ArrayList<Phone> getAllPhone() {
ArrayList<Phone> list = new ArrayList<>();
ResultSet rs = pstmt.executeQuery();
try {
while (rs.next()) {
Phone phone = new Phone();
phone.setId(rs.getInt("id"));
phone.setName(rs.getString("name"));
phone.setPrice(rs.getInt("price"));
phone.setQuantity(rs.getInt("quantity"));
phone.setDescription(rs.getString("description"));
System.err.println(phone);
list.add(phone);
}
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
rs.close();
}
return list;
}
Note how the ResultSet is closed in a finally block to stop leaks.
There are variations of this pattern which, for example, only create the connection and prepare the statement at the last minute rather than as static final fields like I have here.
I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly
I checked everything like username, password, db_url, table name, etc but still I get this output---connecting to database
creating statement
java.lang.NullPointerException
here is my code, (I'm using eclipse Kepler EE and MySQL 5.6.17.0)
import java.sql.*;
public class Demo {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sample";
static final String USER="root" ;
static final String PASS="root";
public static void main(String[] args)
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
conn=DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("creating statement");
String sql="select * from sample";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int eid=rs.getInt("id");
String ename=rs.getString("name");
System.out.print(eid+"\t");
System.out.print(ename);
System.out.println("");
}
rs.close();
stmt.close();
conn.close();
}catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
}
}catch(Exception e)
{
System.out.println(e);
}
try
{
if(conn!=null)
{
conn.close();
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
}
I don't think your statement is set. It is always null.
I think you should use this:
stmt = conn.createStatement( );
You didnt create stmt object
stmt = conn.createStatement( );
You have to add above line before this line ResultSet rs=stmt.executeQuery(sql);
You are executing query on a null object.
So getting NPE
You set Statement stmt=null; and you never initialize it later.