Cannot retrieve data into Jtextfield from MySql Database - java

try
{
st=cn.createStatement();
String strUser="";
rs=st.executeQuery("SELECT * FROM chsl_db WHERE name='"+nametxt.getText()+"'");
while(rs.next())
{
strUser=rs.getString(1);
}
if(strUser.equals(nametxt.getText()))
{
st= cn.createStatement();
rs = st.executeQuery("SELECT * FROM chsl_db WHERE name ='" + nametxt.getText() + "'");
while (rs.next())
{
titletxt.setText(rs.getString(1));
nametxt.setText(rs.getString(2));
flatnum.setText(rs.getString(3));
areatxt.setText(rs.getString(4));
emailtxt.setText(rs.getString(5));
deletebutton.setEnabled(true);
}
st.close();
}
else
{
JOptionPane.showMessageDialog(null,"No Data Found!","Security Warning",JOptionPane.WARNING_MESSAGE);
}
}
catch(SQLException s)
{
System.out.println("No record found!\n\n\n");
System.out.println("SQL Error" + s.toString() + " " + s.getErrorCode() + " " + s.getSQLState());
}
catch(Exception x)
{
System.out.println("Error" + x.toString()+" " + x.getMessage());
}
}
Project on Netbeans Using MySql Workbench as Database. Insert Data into Database is Working but cannot retrieve the same. It throws error "No Data Found!". Checked the connection and its ok. Below are the codes that i used to establish connection. Please Help !!
try
{
Class.forName("java.sql.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/avinash?useSSL=false","root","password");
}
catch(ClassNotFoundException e)
{
System.err.println("Failed to load driver");
e.printStackTrace();
}
catch(SQLException e)
{
System.err.println("Unable to connect");
e.printStackTrace();
}

add st=cn.createStatement(); in your connection after line below.
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/avinash?useSSL=false","root","password");
i don't get in what you need to do.
but i think in beginning would be
try {
nm = nametxt.getText();
if(nm != '') {
rs = st.executeQuery("SELECT * FROM chsl_db WHERE name ='" + nm + "'");
while (rs.next()) {
titletxt.setText(rs.getString(1));
nametxt.setText(rs.getString(2));
flatnum.setText(rs.getString(3));
areatxt.setText(rs.getString(4));
emailtxt.setText(rs.getString(5));
deletebutton.setEnabled(true);
}
st.close();
}
else {
JOptionPane.showMessageDialog(null,"No Data Found!","Security Warning",JOptionPane.WARNING_MESSAGE);
}
}
its been a while i'm not using Netbeans. So tell me if i was wrong.

Related

Error: Parameter index out of range (1 > number of parameters, which is 0)

I'm making a Login form using JSP + JDBC + Servlet.
Whenever I tried to login a username a username and password, I get this error:
SQLState: S1009
Error Code: 0
Message: Parameter index out of range (1 > number of parameters, which is 0)
public class LoginDao {
public boolean validate(LoginBean loginBean) throws ClassNotFoundException {
boolean status = false;
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop?user=root", "root", "12301230");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from myshop.userlogin WHERE username = '?' and password = '?' ")) {
preparedStatement.setString(1, loginBean.getUsername());
preparedStatement.setString(2, loginBean.getPassword());
System.out.println(preparedStatement);
ResultSet rs = preparedStatement.executeQuery();
status = rs.next();
} catch (SQLException e) {
// process sql exception
printSQLException(e);
}
return status;
}
private void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
I actually haven't tried that much other than restarting my database and creating a new table. I'm actually new to this language and I only got this source code on a tutorial.
JDBC will take care of quotes in the query
PreparedStatement preparedStatement =
connection.prepareStatement("SELECT * from myshop.userlogin WHERE username = ? and password = ? ")) {

com.microsoft.sqlserver.jdbc.SQLServerException: The value is not set for the parameter number 1

I have a problem with line pstmt.setLong(1, id);. I get an error that the value is not set for the parameter number 1. If I use the String SQL without the question mark, it works. Also, when I use ARM the PreparedStatement and ResultSet are not automatically closed so I have to close them, and finally doesn't seem to work either
#Override
public Company getCompany(long id) {
Connection con = ConnectionPool.getInstance().getConnection();
String sql = "SELECT * FROM Company WHERE ID=?";
//String sql = "SELECT * FROM Company WHERE ID=" + id;
Company company = new Company();
try (
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();)
{
pstmt.setLong(1, id);
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
pstmt.close();
rs.close();
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}
ConnectionPool.getInstance().returnConnection(con);
return company;
}
Set the parameter before executing the query.
Also, You don't need to close Statement and result sets defined in try-with-resource statements as they'll be closed automatically when you leave the try scope.
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try(ResultSet rs = pstmt.executeQuery()) {
// do stuff
}
}
You need to set the PreparedStatement's parameters before executing it. Also note that this you're using the try-with-resource syntax you shouldn't close the resources yourself:
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
}
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}

Connecting to different schemas using prepared statement

I have the following code running fine with one sql statement selectEmpShowDocs_SQL referring to schema1. In this scenario, I have hard coded the value of empID as 2 as shown in the sql below :
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
Now, I have another sql statement which is retrieving the emp_id value and instead of hardcoding the value just like I did above for empID, I want to pass the value of emp_id obtained from the following sql statement to the above sql statement. This is the statement which is referring to schema2.
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "
I am wondering is it possible to connect with two different schemas with one prepared statement? Here someone mentioned that prepared statement is bound to a specific database and in that case if it's not possible, what would be the best approach for me?
Here is the full code that works fine for me using only the SQL query referring to schema1.
public List<EmployeeDocument> getEmployeeDocument(String docId, Integer employeeID) throws DaoException
{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DataSource ds = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<EmployeeDocument> empShowDocs = new ArrayList<EmployeeDocument>();
try {
ds = jdbcTemplate.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(selectEmpShowDocs_SQL);
logger.debug("sql query :" + selectEmpShowDocs_SQL);
System.out.println(selectEmpShowDocs_SQL);
pstmt.setString(1, docId);
logger.debug("sql parameters, docId:" + docId);
rs = pstmt.executeQuery();
while(rs.next()) {
EmployeeDocument empShowDocRecord = new EmployeeDocument();
empShowDocRecord.setEmp_Content(rs.getString("emp_doc")));
empShowDocs.add(empShowDocRecord);
}
} catch(Throwable th) {
throw new DaoException(th.getMessage(), th);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (pstmt != null) {
try {
pstmt.close();
} catch(SQLException sqe) {
sqe.printStackTrace();
}
pstmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
conn = null;
}
if (ds != null) {
ds = null;
}
}
return empShowDocs;
}
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "

How to copy selected items from one array to another?

Is there any way to create an array from another?, In my case I have a list, this list has checkboxes, each row, until now I can get the value of the checkboxes checked. Now my question is: Can I get those checkbox values and make another array from them?
if (accion.equalsIgnoreCase("agregar")) {
List<Directorio> listaDirectorio = DirectorioDAO.getListDirectorio(request.getParameter("a_selectCta"));
request.setAttribute("a_listaDirectorio", listaDirectorio);
String select[] = request.getParameterValues("a_checkCta");
for (int i = 0; i < select.length; i++) {
directorio = DirectorioDAO.getDirectorio(Integer.parseInt(select[i]));
System.out.println(select[i]);
System.out.println(directorio);
}
request.setAttribute("a_accion","agregar");
}
getDirectorio Method:
public static Directorio getDirectorio(int idDirectorio) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
Directorio directorio=null;
try {
connection = ConnectionDBM.getConnection();
if (connection != null) {
String sql = " SELECT id_directorio, id_ctahabiente, nombre_completo,cargo, calle_numero, "
+ " colonia, delegacion, CP, estado, telefono1, telefono2, ext1, ext2, correo, "
+ " observaciones, tipo, confirmado, principal, fechaModificacion "
+ " FROM DIRECTORIO WHERE id_directorio = ? ";
statement = connection.prepareStatement(sql);
statement.setInt(1, idDirectorio);
rs = statement.executeQuery();
if(rs.next()) {
directorio= new Directorio();
directorio.setIdDirectorio(rs.getInt("id_directorio"));
directorio.setIdCtahabiente(rs.getString("id_ctahabiente"));
directorio.setNombreCompleto(rs.getString("nombre_completo"));
directorio.setCargo(rs.getString("cargo"));
directorio.setCalleNumero(rs.getString("calle_numero"));
directorio.setColonia(rs.getString("colonia"));
directorio.setDelegacion(rs.getString("delegacion"));
directorio.setCP(rs.getString("CP"));
directorio.setEstado(rs.getString("estado"));
directorio.setTelefono1(rs.getString("telefono1"));
directorio.setTelefono2(rs.getString("telefono2"));
directorio.setExt1(rs.getString("ext1"));
directorio.setExt2(rs.getString("ext2"));
directorio.setCorreo(rs.getString("correo"));
directorio.setObservaciones(rs.getString("observaciones"));
directorio.setTipo(rs.getString("tipo"));
directorio.setConfirmado(rs.getBoolean("confirmado"));
directorio.setPrincipal(rs.getBoolean("principal"));
directorio.setFechaModificacion(rs.getDate("fechaModificacion"));
}
}
} catch (SQLException e) {
logger.error("getRegControl: ", e);
throw new RuntimeException(e);
} catch (Exception e) {
logger.error("getRegControl: ", e);
throw new RuntimeException(e);
} finally {
try {
statement.close();
} catch (Exception e) {
}
try {
rs.close();
} catch (Exception e) { }
try {
if (connection != null && !connection.isClosed())
connection.close();
} catch (Exception e) {}
}
return directorio;
}
In answer to your question you can aither by using a collection and using an addAll method or by using System.arrayCopy
But to be honest why does not change you query so that in it queries for all selected ids.
SELECT id_directorio, id_ctahabiente, nombre_completo,cargo, calle_numero, "
+ " colonia, delegacion, CP, estado, telefono1, telefono2, ext1, ext2, correo, "
+ " observaciones, tipo, confirmado, principal, fechaModificacion "
+ " FROM DIRECTORIO WHERE id_directorio IN ?
And then you will speed up your query and have cleaner code.
see https://stackoverflow.com/questions/13254133/jdbc-prepared-statement-how-to-set-a-list

Getting SQL error 1078 Before start of result set in Java program [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
I have a Java method that is supposed to get column values from one MySQL row and create a string with the values. When run, it generates a SQL error 1078 "Before start of result set."
Here is the the class in which the error is occuring (Problem is in listPosesInSection method:
/** Class used to access the database */
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class YogaDatabaseAccess {
String dbUrl = "jdbc:mysql://localhost/yoga";
private Connection connection;
private ResultSet rset;
private ResultSetMetaData rsMetaData;
private Statement statement;
private PreparedStatement pStatementAll = null;
private PreparedStatement pStatementPartial = null;
// Strings for queries and updates
String strListPosesNotPrimary;
String strInsertNewClass;
String strInsertNewSection;
String strInsertNewPose;
String strUpdateClass;
String strUpdateSection;
String strUpdatePose;
String strArrangePoseOrder;
private String[] poseArray;
// Constructor
YogaDatabaseAccess() {
connectToDatabase();
}
// Method that connects to database
private void connectToDatabase() {
try {
connection = DriverManager.getConnection(dbUrl, "Kyle", "Kullerstrand#2");
System.out.println("Database connected");
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
// Query that returns lists to be used with combo boxes
public String listForBoxes(String listName) {
// List to be returned
String strList = "";
// Determine name of the database table for this list
String listTableName;
if (listName == "pose")
listTableName = listName + "s";
else if (listName == "class")
listTableName = listName + "es";
else
listTableName = listName;
// Determine the database column name for this list
String listColumnName = listName + "_name";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT " + listColumnName + " FROM " + listTableName +
" ORDER BY " + listColumnName);
while (rset.next()){
strList = strList + rset.getString(listColumnName) + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns list of primary poses for a section
public String listPrimaryPoses(String sectionName) {
// List to be returned
String strList = "";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE primarily_suitable_for = '" + sectionName +
"' OR primarily_suitable_for = 'Anything' ORDER BY pose_name");
while (rset.next()){
strList = strList + rset.getString("pose_name") + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns list of secondary poses for a section
public String listSecondaryPoses(String sectionName) {
// List to be returned
String strList = "";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE sometimes_suitable_for = '" + sectionName + "' ORDER BY pose_name");
while (rset.next()){
strList = strList + rset.getString("pose_name") + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns the poses within a specific section
public String listPosesInSection(String tableName, String sectionName) {
String strList;
StringBuilder strBuilderList = new StringBuilder("");
// Run the query
try {
statement = connection.createStatement();
// Query will collect all columns from one specific row
rset = statement.executeQuery("SELECT * FROM " + tableName + " WHERE " + tableName + "_name = '" + sectionName + "'");
while (rset.next()) {
for (int i = 2; i <= countColumnsInTable(tableName); i++) // First value (0) is always null, skip section name (1)
if (rset.getString(i) != null) // If column has a value
strBuilderList.append(rset.getString(i) + "\n");
}
} catch (SQLException e) {
e.printStackTrace();
}
strList = strBuilderList.toString();
return strList.replaceAll(", $",""); // Strips off the trailing comma
}
// Insert statement that inserts a new class into the classes table
public void insertNewClass(String className) {
/** String insert = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
System.out.println("About to create the prepared statement");
// Run the insert
try {
pStatement = connection.prepareStatement(insert);
// statement.execute("INSERT IGNORE INTO poses VALUES ('" + poseName + "', '" + suitableFor + "', '" + suitableForSometimes + "')");
pStatement.setString(1, poseName);
pStatement.setString(2, suitableFor);
pStatement.setString(3, suitableForSometimes);
System.out.println("Created the prepared statement");
// execute query, and return number of rows created
pStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} */
}
// Insert statement that inserts a new pose into poses table
public void insertNewPose(String poseName, String suitableFor, String suitableForSometimes) {
String insertAll = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
String insertPartial = "INSERT INTO poses (pose_name, primarily_suitable_for) values(?, ?)";
// Run the insert
try {
if (suitableForSometimes == "NULL") { // Insert statement contains a null value for sometimes suitable column
pStatementPartial = connection.prepareStatement(insertPartial);
pStatementPartial.setString(1, poseName);
pStatementPartial.setString(2, suitableFor);
pStatementPartial.executeUpdate();
} else { // Insert statement contains values for all three columns
pStatementAll = connection.prepareStatement(insertAll);
pStatementAll.setString(1, poseName);
pStatementAll.setString(2, suitableFor);
pStatementAll.setString(3, suitableForSometimes);
pStatementAll.executeUpdate();
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "This pose already exists.");
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
}
}
}
// Insert statement that inserts a new section into warmup, work or restore sections
public void insertNewSection(String sectionType, String sectionName, ArrayList<String> poses) {
System.out.println("insertNewSection method was called");
int maxColumns = countColumnsInTable(sectionType);
poseArray = new String[poses.size()];
poseArray = poses.toArray(poseArray);
if (poseArray.length == 0)
JOptionPane.showMessageDialog(null, "There are no poses in this section. Please add poses.");
// Create a list of columns of the table for the INSERT statement
StringBuilder columns = new StringBuilder(sectionType + "_name");
for (int c = 1; c < maxColumns; c++)
columns.append(", pose_" + c);
// Create a string list of poses, separated by commas, from the array
StringBuilder values = new StringBuilder();
values.append("'" + poseArray[0] + "'");
for (int v = 1; v < poseArray.length - 1; v++)
values.append(", '" + poseArray[v] + "'");
// make sure query uses correct number of columns by padding the query with NULL
for (int i = poseArray.length; i < maxColumns; i++)
values.append(", NULL");
String posesToAddToSection = values.toString();
// The string containing the entire insert statement
String insert = "INSERT INTO " + sectionType + " (" + columns + ") VALUES ('" + sectionName + "', " + posesToAddToSection + ")";
// Run the insert
try {
statement = connection.createStatement();
statement.executeUpdate(insert);
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "An error in the yoga design program has occurred. SQLException: " +
e.getMessage() + ":" + e.getSQLState());
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
}
}
}
// Statement that deletes rows from tables
public void deleteRow(String tableName, String columnName, String rowName) {
String delete = "DELETE FROM " + tableName + " WHERE " + columnName + " = '" + rowName + "'";
// Run the insert
try {
statement = connection.createStatement();
statement.executeUpdate(delete);
System.out.println("Delete statement was run on Java's end.");
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "Sorry, something went wrong: SQLException: " +
e.getMessage() + ":" + e.getSQLState());
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method for getting the number of columns in a table using metadata
public int countColumnsInTable(String sectionType) {
int count = 16;
try {
// System.out.println(sectionType);
statement = connection.createStatement();
rset = statement.executeQuery("SELECT * FROM " + sectionType);
rsMetaData = rset.getMetaData();
count = rsMetaData.getColumnCount();
// System.out.println("Column count is " + count);
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
// Close the database and release resources
public void closeDatabase() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And here is the beginning of the error list:
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:855)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5693)
at YogaDatabaseAccess.listPosesInSection(YogaDatabaseAccess.java:125)
at YogaSectionDesigner$5.actionPerformed(YogaSectionDesigner.java:229)
May be you can check this out:
ResultSet exception - before start of result set
Had the same Problem. Solved it that way.

Categories

Resources