I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}
Related
I have database studentdb and table name student in MySQL. what should i do in order to insert the data and fetch complete table from the database. username is "root" and password is also "root".
I want to insert data in table and after that I want to display the table data content.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/studentdb","root","root");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
String query = "SELECT * FROM student";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("pass");
// print the results
System.out.format("%s, %s, %s\n", name, email, password);
}
st.close();
}
catch(Exception se)
{
se.printStackTrace();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}`enter code here`
There are 3 columns in database "name", "email", "pass".
Can someone please tell me what is wrong to my query.
I have textbox to update the occupantname but it doesn't work, Only Status works.
String gOccupied = "Occupied" ;
String query = "UPDATE `rooms` SET `occupantname` = '"+txtFirstNames.getText()+"' , `status`='"+gOccupied+"' WHERE roomnumber = " +CBRoomNumber.getSelectedItem();
executeSQlquery(query,""+" Updated");
Can someone please tell me what is wrong to my query. i have textbox
to update the occupantname but it doesn't work, Only Status works.
Don't use direct MySql SQL with these special characters `
String query = "UPDATE rooms SET occupantname =
'"+txtFirstNames.getText()+"' , status='"+gOccupied+"' WHERE
roomnumber = " +CBRoomNumber.getSelectedItem();
Blockquote
Instated Use below SQL
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
private static PreparedStatement preparedStmt = null;
private static Connection connection = null;
public static void main(String[] args) {
String gOccupied = "Occupied";
String occupantname = txtFirstNames.getText();
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
try {
executeSQlquery(query, occupantname, gOccupied, "Updated");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeSQlquery(String query, String occupantname, String gOccupied, String status) throws SQLException {
try {
// create a java mysql database connection
String myDriver = "org.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
connection = DriverManager.getConnection(myUrl, "username", "password");
preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, occupantname);
preparedStmt.setString(2, gOccupied);
preparedStmt.setInt(3, 101);
// execute the java preparedstatement
preparedStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//finally block used to close resources
if (preparedStmt != null) {
connection.close();
}
if (connection != null) {
connection.close();
}
}
}
}
It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
SQL select statement with where clause
I am trying to retrieve the value of a TEXT field from a table in a MySQL database.
MySQL version is 5.6.21
& I am using mysql-connector-java-5.1.18-bin.jar
My file is given below
import java.sql.*;
public class DatabaseConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/book";
// database credentials
static final String USER = "username";
static final String PASS = "password";
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...");
stmt = conn.createStatement();
String query;
query = "Select b_name, description columns from brands";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String first_name = rs.getString("b_name");
String description = rs.getString("description");
System.out.println(first_name);
System.out.println(description);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
} catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
} catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
This says that my column does not exist although I have tried this on another table, it works on VARCHAR columns but not on TEXT columns
This error shows up:
But the table has a column named description:
The problem is NOT about the column type being text.
You can get the value of a TEXT type using getString.
You can verify in the documentation.
The problem is in the query:
query = "Select b_name, description columns from brands";
"columns" there is a mistake.
Written this way, the description column is in fact renamed to columns in your result set.
If you did rs.getString("columns") you would get the value.
But that's not what you want to do. You want to fix the query by dropping that word:
query = "Select b_name, description from brands";
I used mysql-connector-java-5.1.38 to operate mysql-community-5.7.10.0 on Windows 10 64-bit.
I try to bind value in limit for pagination
"SELECT * FROM employee LIMIT ?, ?"
However the result shows:
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 '?, ?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2505)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1370)
at SqlTest.main(SqlTest.java:65)
However, I tried sql in navicat directly but could get the correct answer:
INSERT INTO employee VALUES (1, 'Zara');
INSERT INTO employee VALUES (2, 'Zara');
INSERT INTO employee VALUES (3, 'Zara');
INSERT INTO employee VALUES (4, 'Zara');
SET #skip=1; SET #numrows=5;
PREPARE STMT FROM 'SELECT * FROM employee LIMIT ?, ?';
EXECUTE STMT USING #skip, #numrows;
Here is my entire code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/employee?useServerPrepStmts=false";
// Database credentials
static final String USER = "root";
static final String PASS = "whaty123";
static final int PAGESIZE = 10;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pStmt = null;
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
}
String insertPreparedSql = "INSERT INTO employee " + "VALUES (?, 'Zara')";
try {
pStmt = conn.prepareStatement(insertPreparedSql);
} catch (SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
try {
pStmt.setInt(1, i);
pStmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
String selectLimitSql = "SELECT * FROM employee LIMIT ?, ?";
// select with limit
try {
pStmt = conn.prepareStatement(selectLimitSql);
pStmt.setFetchSize(PAGESIZE);
pStmt.setMaxRows(PAGESIZE);
pStmt.setFetchDirection(ResultSet.FETCH_FORWARD);
int pageNo = 0;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
ResultSet rs = pStmt.executeQuery(selectLimitSql);
while (!rs.wasNull()) {
while(rs.next()) {
System.out.println("id: " + String.valueOf(rs.getInt(1)) + " name: " + rs.getString(2));
}
pageNo = pageNo + 1;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
pStmt.executeQuery(selectLimitSql);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Your problem is not about the syntax or MySQL support for LIMIT since it's supported. The problem is about the way you are executing the PreparedStatement.
When using PreparedStatement you may not use the executeQuery(String sql), because you've prepared the SQL string formerly for the execution, and no need to pass it again in the executeQuery() method. So do this
ResultSet rs = pStmt.executeQuery();
instead of
ResultSet rs = pStmt.executeQuery(selectLimitSql);
With passing again the selectLimitSql (like above line), you are ignoring the following lines:
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
and it is like executing your primitive pure sql which contains '?, ?' place holders and you get that exception.
You do not need to pass the query string. Do this
ResultSet rs = pStmt.executeQuery();
instead of
ResultSet rs = pStmt.executeQuery(selectLimitSql);
Also, remove the following lines as pagination is taken care of limit in query itself.
pStmt.setFetchSize(PAGESIZE);
pStmt.setMaxRows(PAGESIZE);
pStmt.setFetchDirection(ResultSet.FETCH_FORWARD);
Following code works:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/company?useServerPrepStmts=false";
// Database credentials
static final String USER = "root";
static final String PASS = "rohan";
static final int PAGESIZE = 10;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pStmt = null;
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
}
String insertPreparedSql = "INSERT INTO employee " + "VALUES (?, 'Zara', 'Zara','Zara')";
try {
pStmt = conn.prepareStatement(insertPreparedSql);
} catch (SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
try {
pStmt.setInt(1, i*10);
pStmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
String selectLimitSql = "SELECT * FROM employee limit ?, ?";
// select with limit
try {
pStmt = conn.prepareStatement(selectLimitSql);
int pageNo = 0;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
ResultSet rs = pStmt.executeQuery();
while (!rs.wasNull()) {
while(rs.next()) {
System.out.println("id: " + String.valueOf(rs.getInt(1)) + " name: " + rs.getString(2));
}
pageNo = pageNo + 1;
pStmt.setInt(1, pageNo * PAGESIZE);
pStmt.setInt(2, PAGESIZE);
rs = pStmt.executeQuery();
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I have a null pointer exception in
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
my code is like this :
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}
Most likely aStatement is null.
Sounds like you think aStatement should not be null, but it is.
This is bad JDBC code, for many reasons:
No cleanup of resources.
Doesn't use PreparedStatement
Keeps creating the query string over and over again instead of using a static variable
Doesn't follow Java coding standards ("Query" should be "query")
Here's another way to write it. Start with an interface:
package persistence;
import java.sql.SQLException;
public interface CredentialDao
{
boolean isValidUser(String username, String password) throws SQLException;
}
Write an implementation:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CredentialDaoImpl implements CredentialDao
{
private static final String CREDENTIAL_QUERY = "SELECT COUNT() FROM USER WHERE USERNAME = ? AND PASSWORD = ?";
private Connection connection;
public CredentialDaoImpl(Connection connection)
{
this.connection = connection;
}
public boolean isValidUser(String username, String password) throws SQLException
{
boolean isValidUser = false;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = this.connection.prepareStatement(CREDENTIAL_QUERY);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next())
{
int count = rs.getInt(1);
isValidUser = (count > 0);
}
}
finally
{
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return isValidUser;
}
}
The aStatement variable is apparently null, please validate that it is correctly set. You should consider read the Java Naming Conventions and make sure you use the lower camel case for variables and java bean conventions.
For code snippets in stackoverflow if they are not self-explanatory, you should obey the rules of the SSCCE, this will help you to get more and better answers. Also you should provide a stack trace with the occured exception.
Use prepared statements.
Connection con = ...; // obtain connection here
PreparedStatement pstmt = con.prepareStatement("select * from TBL_Users where userName = ?'");
pstmt.setInt(1, userName);
ResultSet rs = pstmt .executeQuery();
...
// do clean up here
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true; // Huh? What?
}
What is info refering to and why is there a return imediatly after the assignments?