Resultset.next() while loop prints twice and - java

I'm trying this tutorial code and it seems to print out my database from MySQL twice. It comes from this while loop below:
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
String user = resultSet.getString("myuser");
String email = resultSet.getString("email");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Email: " + email);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
That loop prints out twice. If I put a break statement at the end of the loop, it still prints the first row of my database twice. I think it has something to do with resultSet.next(). Here is the full code below:
package de.vogella.mysql.first;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009-12-11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, email, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
String user = resultSet.getString("myuser");
String email = resultSet.getString("email");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Email: " + email);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}

Related

having trouble inserting values into table with syntax error

Everytime at around "composedLine = String.format("%s, %s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);"
it produces "INSERT INTO airport VALUES (, ABR, Aberdeen Regional Airport, Aberdeen"
instead of "INSERT INTO airport VALUES (ABR, Aberdeen Regional Airport, Aberdeen"
which causes a syntax error when I use executeupdate due to the "," before the ABR.
import java.io.*;
import java.sql.*;
import java.util.*;
public class UsaDelayFlight {
public static Connection connectToDatabase(String user, String password, String database) {
System.out.println("------ Testing PostgreSQL JDBC Connection ------");
Connection connection = null;
try {
String protocol = "jdbc:postgresql://";
String dbName = "";
String fullURL = protocol + database + dbName + user;
connection = DriverManager.getConnection(fullURL, user, password);
} catch (SQLException e) {
String errorMsg = e.getMessage();
if (errorMsg.contains("authentication failed")) {
System.out.println("ERROR: \tDatabase password is incorrect. Have you changed the password string above?");
System.out.println("\n\tMake sure you are NOT using your university password.\n"
+ "\tYou need to use the password that was emailed to you!");
} else {
System.out.println("Connection failed! Check output console.");
e.printStackTrace();
}
}
return connection;
}
public static void dropTable(Connection connection, String table) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("DROP TABLE IF EXISTS " + table);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static void createTable(Connection connection, String tableDescription) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("CREATE TABLE IF NOT EXISTS " + tableDescription);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static ResultSet executeQuery(Connection connection, String query) {
System.out.println("DEBUG: Executing query...");
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static int insertIntoTableFromFile(Connection connection, String table,
String filename) {
int numRows = 0;
String currentLine = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
Statement st = connection.createStatement();
// Read in each line of the file until we reach the end.
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
System.out.println(Arrays.toString(values));
String composedLine = "INSERT INTO " + table + " VALUES (";
//String r = String.format("formatted values are %s", composedLine);
composedLine = String.format("%s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);
System.out.println(composedLine);
//. . .
// Finally, execute the entire composed line.
numRows = st.executeUpdate(composedLine);
}
} catch (Exception e) {
e.printStackTrace();
}
return numRows;
}
// NOTE: You will need to change some variables from START to END.
public static void main(String[] argv) throws SQLException {
// START
// Enter your username.
String user = "";
// Enter your database password, NOT your university password.
String password = "";
/** IMPORTANT: If you are using NoMachine, you can leave this as it is.
*
* Otherwise, if you are using your OWN COMPUTER with TUNNELLING:
* 1) Delete the original database string and
* 2) Remove the '//' in front of the second database string.
*/
String database = "";
//String database = "";
// END
Connection connection = connectToDatabase(user, password, database);
if (connection != null) {
System.out.println("SUCCESS: You made it!"
+ "\n\t You can now take control of your database!\n");
} else {
System.out.println("ERROR: \tFailed to make connection!");
System.exit(1);
}
// Now we're ready to use the DB. You may add your code below this line.
createTable(connection, "delayedFlights (ID_of_Delayed_Flight varchar(15) not null, Month varchar(10), "
+ "DayofMonth int, DayofWeek int, DepTime timestamp, ScheduledDepTime timestamp, ArrTime int,"
+ "ScheduledArrTime timestamp, UniqueCarrier varchar(15) not null, FlightNum int, ActualFlightTime timestamp,"
+ "scheduledFlightTime timestamp, AirTime timestamp, ArrDelay timestamp, DepDelay timestamp, Orig varchar(15),"
+ "Dest varchar(15), Distance int, primary key (ID_of_Delayed_Flight), unique (UniqueCarrier));");
createTable(connection, "airport (airportCode varchar(15) not null, "
+ "airportName varchar(15), City varchar(15), State varchar(15), primary key (airportCode));");
insertIntoTableFromFile(connection, "airport", "airport");
String query = "SELECT * FROM delayedFlights;";
ResultSet rs = executeQuery(connection, query);
try {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
}
}
This code is a security vulnerability. Specifically, SQL injection. This is not how you do it.
The correct way also solves your problem in passing. Thus, solution: Do it the correct way, solves all your problems.
Correct way:
PreparedStatement ps = con.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)");
ps.setString(1, values[0]);
ps.setString(2, values[1]);
ps.setString(3, values[2]);
ps.setString(4, values[3]);
ps.executeUpdate();

how to check for duplicate inputs and prevents it to be added to the database

Hello guys how can I check duplicate inputs (adding students) and how to prevent it. It says that when i create a table the inputs that I've been inserting the database is all a duplicate which is obviously not. In line with that how can I detect and check of the inserted input is a duplicate of the previous inputs.This is the first output in my console This is the continuation
Here is my code:
Main.java
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 Main {
public static void main (String args[]) throws Exception {
StudentDAO x1= new StudentDAO();
x1.getConnection();
x1.makeTable(); //create Table
x1.addstud("1","Yves Francisco", "2000000001","5","CpE","Male");
x1.addstud("2","Lance Eco", "2000000002","5","CpE","Male");
x1.addstud("3","Karlos Castillo", "2000000003","5","CpE","Male");
x1.addstud("4","Glenn Bordonada", "2000000004","5","ECE","Male");
x1.addstud("5","JM Enriquez", "2000000005","5","ECE","Male");
x1.addstud("6","John Martinez", "2000000006","2","ECE","Male");
x1.addstud("7","Timothy Tolentino", "2000000007","4","IT","Male");
x1.addstud("8","Kyle Dacaymat", "2000000008","3","CpE","Male");
x1.addstud("9","Dom Benedictos", "2000000009","1","IT","Male");
x1.addstud("10","Lance Roque", "2000000010","1","ECE","Male");
x1.addstud("11", "Vegeta", "2000000011", "1", "ME", "Male"); // added Student
//x1.addstud("12", "Vegeta", "2000000011", "1", "ME", "Male"); // pang check if entered input is a duplicate of a field of studName, studNumber, etc.
//x1.delstud(); // delete student
//x1.updstuddb();
x1.showdb();
}
}
StudentDAO.java
//import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//import java.sql.ArrayList;
public class StudentDAO {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void showdb() throws Exception
{
try {
Connection con = getConnection();
String query = "SELECT *FROM studinfo;";
PreparedStatement showstuddb= con.prepareStatement(query);
ResultSet rs = showstuddb.executeQuery();
System.out.println("Showing Database.....................");
System.out.println("============================================================# THE CONTENT OF THE DATABASE #============================================================");
while (rs.next())
{
String idko = rs.getObject(1).toString();
String ngalan = rs.getObject(2).toString();
String numko=rs.getObject(3).toString();
String baitang=rs.getObject(4).toString();
String kurso=rs.getObject(5).toString();
String kasarian=rs.getObject(6).toString();
System.out.println("My ID number is: "+ idko + " Name is: " + ngalan + " Student Number is: " + numko + " Year/Level is: "+ baitang +" Course is: " + kurso + " Sex is: " + kasarian);
}
showstuddb.close();
System.out.println("Nothing follows.....................");
con.close();
}
catch (Exception e)
{
System.out.println("Error on showing contents of database!!!" + e.getMessage());
}
}
public void updstuddb () throws Exception
{
try {
Connection con = getConnection();
String query = "UPDATE studinfo SET studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=? WHERE studid=?";
PreparedStatement studup = con.prepareStatement(query);
studup.setString(1, "Kakarot"); //This will be the replacement
studup.setString(2, "2000000020");
studup.setString(3, "2");
studup.setString(4, "IT");
studup.setString(5, "dafq");
studup.setString(6, "1");// The unique element among the content of the database which is used to determine which is to update
studup.executeUpdate();
System.out.println("THE LIST HAS BEEN UPDATED ############################################################");
studup.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error in updating the database!!!" + e.getMessage());
}
}
public void delstud()
{
try {
Connection con = getConnection();
String query = "DELETE FROM studinfo WHERE studid=?";
PreparedStatement userdel = con.prepareStatement(query);
userdel.setString(1, "12"); // To determine what to delete in the Database
//userdel.setString(1, "2000000002");
//userdel.setString(1, "2000000003");
//userdel.setString(1, "2000000004");
//userdel.setString(1, "2000000005");
//userdel.setString(1, "2000000006");
//userdel.setString(1, "2000000007");
//userdel.setString(1, "2000000008");
//userdel.setString(1, "2000000009");
//userdel.setString(1, "2000000010");
userdel.execute();
userdel.close();
System.out.println("Data is now deleted!!!");
con.close();
}
catch (Exception e)
{
System.out.println("Error!!!. Data is not deleted " + e.getMessage());
}
}
public void addstud(String studid, String studName, String studNum, String studYrLvl, String studKors, String studGender) throws Exception
{
//String var1 = "Yves Francisco";
//String num1 = "2000000001";
//String num2 = "5";
//String var2 = "CpE";
//String var3 = "Male";
try {
Connection con = getConnection();
PreparedStatement posted= con.prepareStatement("INSERT INTO studinfo (studid, studName, studNum, studYrLvl, studKors, studGender) VALUES (?,?,?,?,?,?)");
int y=1;
posted.setString(y++, studid);
posted.setString(y++, studName);
posted.setString(y++, studNum);
posted.setString(y++, studYrLvl);
posted.setString(y++, studKors);
posted.setString(y++, studGender);
posted.executeUpdate(); // Manipulate or Update table
posted.close();
//con.close();
}
catch (Exception e)
{
System.out.println("Error on adding columns!!!" + e.getMessage());
}
finally
{
System.out.println("Insert Successful!");
}
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
ResultSet rs=checkdup.executeQuery();
while (rs.next())
{
boolean dup1=rs.getObject(2).equals(studName);
boolean dup2=rs.getObject(3).equals(studNum);
boolean dup3=rs.getObject(4).equals(studYrLvl);
boolean dup4=rs.getObject(5).equals(studKors);
boolean dup5=rs.getObject(6).equals(studGender);
System.out.println("The name you entered is: " + dup1 + " The student number you entered is: " + dup2 + " The Yr/Lvl you entered: " + dup3 + " The Course you entered: " + dup4 + " The Sex you entered is: " + dup5);
}
con.close();
}
catch (Exception e)
{
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
}
public void makeTable() throws Exception
{
try
{
Connection con= getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS studinfo (studid INT NOT NULL AUTO_INCREMENT PRIMARY KEY, studName varchar(255), studNum varchar(30), studYrLvl varchar(2), studKors varchar(30), studGender varchar(10));");
create.executeUpdate();
System.out.println("TABLE IS CREATED!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
create.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error on creating table!!. Table not created!"+e.getMessage());
}
finally
{
System.out.println("Table created!");
};
}
public Connection getConnection () throws Exception {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String username= "root";
String password = "root";
Class.forName(driver);
Connection conn= DriverManager.getConnection(url, username, password);
System.out.println("You are now Connected!!");
return conn; // Return if it is successfully connected!
}
catch (Exception e)
{
System.out.println("Connection not Established!"+e.getMessage());
}
return null; // Return if unsuccessful
}
}
The problem is not a duplicate value in your table, the problem is that you have a mistake in your code.
I wouldn't do it the way you do, because if you use a Try-Catch, anyway there is a problem or a mistake in your code (looking for duplicates) it will answer that you have a duplicate.
Otherwise, even if you have thousands of duplicates, if you don't get an error you won't get a duplicate.
Anyways, the mistake you have in your code is that you don't give any value to the checkdup prepared statement, you should change it to something like this:
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
checkdup.setString(1, studName);
checkdup.setString(2, studNum);
checkdup.setString(3, studYrLvl);
checkdup.setString(4, studKors);
checkdup.setString(5, studGender);
ResultSet rs=checkdup.executeQuery();
while (rs.next())
{
boolean dup1=rs.getObject(2).equals(studName);
boolean dup2=rs.getObject(3).equals(studNum);
boolean dup3=rs.getObject(4).equals(studYrLvl);
boolean dup4=rs.getObject(5).equals(studKors);
boolean dup5=rs.getObject(6).equals(studGender);
System.out.println("The name you entered is: " + dup1 + " The student number you entered is: " + dup2 + " The Yr/Lvl you entered: " + dup3 + " The Course you entered: " + dup4 + " The Sex you entered is: " + dup5);
}
con.close();
}
catch (Exception e)
{
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
EDIT
There is an easy way to look for duplicates, you just count how many you have like in this code:
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
checkdup.setString(1, studName);
checkdup.setString(2, studNum);
checkdup.setString(3, studYrLvl);
checkdup.setString(4, studKors);
checkdup.setString(5, studGender);
ResultSet rs=checkdup.executeQuery();
int dup=0;
while (rs.next())
{
dup+=1;
}
if (dup>1 ) {
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
con.close();
}
catch (Exception e)
{
System.out.println("There is an error ");
}
In your INSERT statement, you also need to change things. The studid is an autoincrement column, so you don't have to put it in your INSERT. It should be like:
Connection con = getConnection();
PreparedStatement posted= con.prepareStatement("INSERT INTO studinfo (studName, studNum, studYrLvl, studKors, studGender) VALUES (?,?,?,?,?)");
int y=1;
posted.setString(y++, studName);
posted.setString(y++, studNum);
posted.setString(y++, studYrLvl);
posted.setString(y++, studKors);
posted.setString(y++, studGender);
posted.executeUpdate(); // Manipulate or Update table
posted.close();

How to validate data using sql statement to ensure user does not breach the system

I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}

Java sql Data pulling in the columnName but not the data

On this java method I am trying to get data from a ms-sql server. I am trying to get the int value from a column , Now the columns I am using are all int's but for some reason when i try pulling it as a INT I am getting a number format error saying that the column is a nvarchar. Not sure what is happening and when i ran the System.out I am noticing I am only pulling the column name but no data that the column has. Here is my method, I am not sure what I am doing wrong or what is missing from this. Any help will be greatly appreciated thank you.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
String type = getTypeOfTimeOff().replaceAll("\\s+","");
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = "SELECT ? FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getTypeOfTimeOff().replaceAll("\\s+",""));
preparedStatement.setString(2, getEmpName());
preparedStatement.setString(3, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
//int checker = rs.getInt(1);
String acheck = rs.getString(1);
System.out.println("TIME off the user has : " + acheck);
int checker = Integer.valueOf(acheck);
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int aCheck = rs.getInt("column name");
}
}catch(){}
like this
For some reason what i did was add an AS to my query along with adding a if statement to my code caused the resultset to work with my code and allowed me to pull numbers from my database. Thank you for your help. Here is the updated code i added if it helps anyone.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = null;
if(getTypeOfTimeOff().equalsIgnoreCase("Vacation Day"))
selectProject = "SELECT VacationDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Bonus Day"))
selectProject = "SELECT BonusDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Birthday Day"))
selectProject = "SELECT BirthdayDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
System.out.println("Query String : " + selectProject);
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getEmpName());
preparedStatement.setString(2, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
int checker = 0 ;
checker = rs.getInt("dayList");
System.out.println("Days the user has off are: " + checker );
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}

Inserting records into a MySQL table using Java

I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

Categories

Resources