Actually, i got a stress in this problem.
I have an image
So Im getting 2 problems here.
How can I insert the auto generate id with format starting "T00001"?
How can i count total number of ID when i display with datas in table.
Im a new one in Java MVC GUI. Anyone can help me get a good solution.
Thanks in advanced
And this is my Data Access Object file.
package model;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class SchoolDAO{
Conexion conexion;
public SchoolDAO(){
conexion = new Conexion();
}
/////INSERT TEACHER
public String insertTeacher(String tbno, String tbname, String tbphone, String tbqualification, String tbexp){
String rptaAdd = null;
try {
Connection accessDB = conexion.getConexion();
CallableStatement cs = accessDB.prepareCall ("{call teacher_insert(?,?,?,?,?)}");
cs.setString(1, tbno);
cs.setString(2, tbname);
cs.setString(3, tbphone);
cs.setString(4, tbqualification);
cs.setString(5, tbexp);
int numFAeffect = cs.executeUpdate();
if(numFAeffect>0){
rptaAdd ="Add successful.";
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, e.toString());
}
return rptaAdd;
}
public ArrayList<School> listTeacher(){
ArrayList listaTeacher = new ArrayList();
School school;
try{
Connection accessDB = conexion.getConexion();
PreparedStatement ps = accessDB.prepareStatement("select * from teacher");
ResultSet rs = ps.executeQuery();
while(rs.next()){
school = new School();
school.setTno(rs.getString(1));
school.setTname(rs.getString(2));
school.setTphone(rs.getString(3));
school.setTqualification(rs.getString(4));
school.setTexp(rs.getString(5));
listaTeacher.add(school);
}
}catch (Exception e){
}
return listaTeacher;
}
}
Send the ID as a number incremented from a sequence or other mechanism that will get you auto incrementing numbers with "T" + left padded string with zeroes to the desired value.
"T" + StringUtils.leftpad(id + "", 5, "0"); // your ID
Select the count (*) from teacher table.
Related
I'm in a Java class and the assignment is to create a table that will show the first ten values of pre-selected columns. However, when I run my code, with the sql running the way it is it says that my table is already created. I was wondering if there was a way for it to stop erroring out when that happens and to still show my code? Also when I set up a new table, the values that I need, (Income, ID, Pep) won't show up, just the headers I established before the syntax will. How would I make these fixes so it stops erroring out and I see my values in the console log?
This is running in eclipse, extended with prior project files from the class i'm taking. I've tried adding prepared statements, attempted to parse for strings to other variables and attempted syntax to achieve the values I need.
LoanProccessing.java file (Main file):
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoanProcessing extends BankRecords {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
BankRecords br = new BankRecords();
br.readData();
Dao dao = new Dao();
dao.createTable();
dao.insertRecords(torbs); // perform inserts
ResultSet rs = dao.retrieveRecords();
System.out.println("ID\t\tINCOME\t\tPEP");
try {
while (rs.next()) {
String ID= rs.getString(2);
double income=rs.getDouble(3);
String pep=rs.getString(4);
System.out.println(ID + "\t" + income + "\t" + pep);
}
}
catch (SQLException e ) {
e.printStackTrace();
}
String s = "";
s=String.format("%10s\t %10s \t%10s \t%10s \t%10s \t%10s ", rs.getString(2), rs.getDouble(3), rs.getString(4));
System.out.println(s);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("Cur dt=" + timeStamp);
Dao.java file:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Dao {
//Declare DB objects
DBConnect conn = null;
Statement stmt = null;
// constructor
public Dao() { //create db object instance
conn = new DBConnect();
}
public void createTable() {
try {
// Open a connection
System.out.println("Connecting to a selected database to create Table...");
System.out.println("Connected database successfully...");
// Execute create query
System.out.println("Creating table in given database...");
stmt = conn.connect().createStatement();
String sql = "CREATE TABLE A_BILL__tab " + "(pid INTEGER not NULL AUTO_INCREMENT, " + " id VARCHAR(10), " + " income numeric(8,2), " + " pep VARCHAR(4), " + " PRIMARY KEY ( pid ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
conn.connect().close(); //close db connection
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}
}
public void insertRecords(BankRecords[] torbs) {
try {
// Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.connect().createStatement();
String sql = null;
// Include all object data to the database table
for (int i = 0; i < torbs.length; ++i) {
// finish string assignment to insert all object data
// (id, income, pep) into your database table
String ID = torbs[i].getID();
double income=torbs[i].getIncome();
String pep=torbs[i].getPep();
sql = "INSERT INTO A_BILL__tab(ID,INCOME, PEP) " + "VALUES (' "+ID+" ', ' "+income+" ', ' "+pep+" ' )";
stmt.executeUpdate(sql);
}
conn.connect().close();
} catch (SQLException se) { se.printStackTrace(); }
}
public ResultSet retrieveRecords() {
ResultSet rs = null;
try {
stmt = conn.connect().createStatement();
System.out.println("Retrieving records from table...");
String sql = "SELECT ID,income,pep from A_BILL__tab order by pep desc";
rs = stmt.executeQuery(sql);
conn.connect().close();
} catch (SQLException se) { se.printStackTrace();
}
return rs;
}
}
Expected results would be printlns for the table functions (inserting records and so on), the headings, the data values for the first 10 files, and the date and time of when the program was run. Actual results were some of the table functions, headings and then the time when the program ran not including when it errors me out with table already created. I'm not exactly sure where or how to fix these issues.
you're getting this exception because every time you run your code, your main method calls dao.createTable();, and if the table is already created, it will throw an exception. So for this part, use a verification to check if the table is already created.
I'm not really sure where you created the variable torbs, but also make sure its properties are not null before inserting them to the database.
I keep getting the following error when I try to upload my books table through eclipse:
java.sql.SQLSyntaxErrorException: ORA-01722: invalid number
I have been able to upload other tables in my database using this basic code, just not this one.
I think it might be something to do with how I am uploading my dates, but I am not sure.
package uploadDatabase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import oracle.jdbc.OracleDriver;
import java.sql.DatabaseMetaData;
import java.sql.Date;
public class StatesTable {
public static void main(String[] args) {
//private static Connection connection;
try{
DriverManager.registerDriver(new OracleDriver());
//make strings for database connections
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String userName = "BOOKSTORE";
String password = "***********";
//make database connection
Connection conn = DriverManager.getConnection(url,userName,password);
DatabaseMetaData meta = conn.getMetaData();
System.out.println(meta.getDatabaseProductVersion());
String isbn[] = {"00000000110","00000000111","00000000112","00000000113","00000000114"};
String title[] = {"THE SHINING", "THE GIRL WITH THE DRAGON TATTO", "PRIDE AND PREJUDICE", "BOSSYPANTS", "THE HUNGER GAMES"};
String author[] = {"STEPHEN KING", "STIEG LARSSON", "JANE AUSTEN", "TINA FEY", "SUZANNE COLLINS"};
String publishDate[] ={"19750115","19990805","18731015","20160105","19821115"};
String edition[] = {"6TH","3RD","26TH","1ST","7TH"};
double cost[] = {15.75,17.95,8.95,9.95,12.95};
String genre[] = {"HORROR", "MYSTERY", "ROMANCE","COMEDY", "ACTION"};
//Database statement for inserting values into BOOKS table
String sqlStatement = "INSERT INTO BOOKS VALUES(?,?,?,?,?,?,?)";
//Prepared statement for database connection
PreparedStatement pstmt = conn.prepareStatement(sqlStatement);
//loop uploads data into database;
for(int i = 0; i < 5; i++){
//insert values into dbms statement
String isb = isbn[i];
String tit = title[i];
String auth = author[i];
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
java.util.Date parsed = df.parse(publishDate[i]);
Date publishDat = new Date(parsed.getTime());
System.out.println(publishDat);
String editio = edition[i];
double cos = cost[i];
String gen = genre[i];
pstmt.setString(1,isb);
pstmt.setString(2,tit);
pstmt.setString(3,auth);
pstmt.setDate(4,publishDat);
pstmt.setString(5,editio);
pstmt.setDouble(6, cos);
pstmt.setString(7, gen);
//Execute update
pstmt.executeUpdate();
}
//close pstmt statement
pstmt.close();
//close database connection
conn.close();
}
catch(SQLException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The reason you are getting this error is because one of the column data types you are passing into the insert command is not the same as what is actually defined. Make sure to check your table and it's column values and data types and make sure those data types align with which you are trying to insert into that database. As what Andreas said in the comment below you should ALWAYS name your columns in INSERT statements, without them you will not know what is going into your database. Hope this helps :)
I'm using the jtbs.jdbc.Driver to verify that a proxy number is stored in my MySQL database.
The problem is that whenever I try to copy the curtain row from the table and put it in my ResultSet, the error says that
there is no current row in the ResultSet
The error is at line 31 String value = result.getString(i);
i have been looking all over the web for answers but none of them seem to help my specific predicament.
UP DATE
so far i added a while(result.next()) and it basically dose nothing the while(result.next()) dose not execute.
Here's my code!!!
package dataBata;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class apples {
ArrayList<String> myList = new ArrayList<String>();
String proxNumber = "2435847564";
String usersName = "user";
String password = "pass";
public void wrightMatchdb(){
Connection conn = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/model";
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(url, usersName, password);
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("select replace(PROXID , ' ','') PROXID ,FIRST_NAME from OKWC_IDCARDS where PROXID = '" + proxNumber + "'");
System.out.println("hello");
while(result.next()){
for(int i=1;i<=6;i++){
System.out.println("hello2");
String value = result.getString(i);
if(result.getString(i) != null){
value = value.replace(" ","");
myList.add(value);
}
String userProx=myList.get(i);
String userFName=myList.get(i+1);
JOptionPane.showMessageDialog(null, userProx + " has a match for", "hi " + userFName, JOptionPane.DEFAULT_OPTION);
}
System.out.println("hello3");
};
System.out.println("hello4");
statement.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
public static void main(String[] args){
apples A = new apples();
A.wrightMatchdb();
}
}
You need to call result.next() before calling result.getString(i)
Moves the cursor forward 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.
As far as I can see, your query returns only 2 columns so if you call result.getString(i), make sure that i is either 1 or 2 otherwise you will get an exception.
I made a class Test which counts the number of entries corresponding to the user id in the database (calling each entry an email). I used 11120059 as id and number of entries corresponding to this in the database is 2. The output of countMail function is working perfectly but because i am returning an array from getMail() function and taking it into new array, it is showing me null pointer exception. Please help I am stuck in middle of this. The code is:
package src.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import model.Email;
import model.User;
public class Test {
public int countMail(User user){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
PreparedStatement myStatement = myConn.prepareStatement("select * from complaints where RID=? ORDER BY date desc");
myStatement.setString(1, user.getId());
ResultSet rs = myStatement.executeQuery();
int count=0;
while(rs.next())
{
count++;
}
return count;
}
catch(Exception e){
e.printStackTrace();
}
return 0;
}
public Email[] getMail(User user){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
PreparedStatement myStatement = myConn.prepareStatement("select * from complaints where RID=? ORDER BY date desc");
myStatement.setString(1, user.getId());
ResultSet rs = myStatement.executeQuery();
Home home= new Home();
int length = home.countMail(user);
Email[] mail = new Email[length];
int i=0;
while(rs.next())
{
mail[i].setMessage((String) rs.getString(5));
mail[i].setTitle((String) rs.getString(4));
mail[i].setSender((String) rs.getString(2));
mail[i].setReceiver((String) rs.getString(1));
i++;
}
return mail;
}
catch (Exception e){
e.printStackTrace();
}
Email[] dummyMail = new Email[1];
return dummyMail;
}
public static void main(String[] args){
Test test = new Test();
User user = new User();
user.setId("11120059");
System.out.println(test.countMail(user));
Email[] email = test.getMail(user);
for (int i=0 ; i<test.countMail(user) ; i++){
System.out.println(email[i].getSender());
}
}
}
And the output is:
2
java.lang.NullPointerException
at src.service.Test.getMail(Test.java:73)
at src.service.Test.main(Test.java:107)
Exception in thread "main" java.lang.NullPointerException
at src.service.Test.main(Test.java:111)
When you write Email[] mail = new Email[length]; you create an array of given length which contains null references. You cannot automatically create all the objects for that array by this command. Add mail[i] = new Email() statement:
Email[] mail = new Email[length];
int i=0;
while(rs.next())
{
mail[i] = new Email(); // or use appropriate constructor parameters
mail[i].setMessage((String) rs.getString(5));
mail[i].setTitle((String) rs.getString(4));
mail[i].setSender((String) rs.getString(2));
mail[i].setReceiver((String) rs.getString(1));
i++;
}
Also note that when you create a dummyMail array, it's also an array with single null-reference, the Email object is not created there as well. Probably you need:
Email[] dummyMail = new Email[] {new Email()};
Problem was:
Can't get just inserted data from the table. From the error message it looks like it doesn't see the first column. I know the column is there and data was inserted. I checked database. I checked if column Number has some hidden space in name. No it doesn't.
Tried:
Debugged every line and everything was good together with inserting data to database.
Found the issue is almost at the end of the code:
rs1.next();
String s1 = rs1.getString(1);
I tried to write
rs1.first();
String s1 = rs1.getString(1);
or
rs1.first();
String s1 = rs1.getString("Number");
Below I posted my final code that is working correctly and I am able to insert data to the table and display on the browser.
package mypackage;
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.Collections;
import java.util.LinkedList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/query")
public class CList {
private LinkedList<SMember> contacts;
public CList() {
contacts = new LinkedList();
}
#GET
#Path("/{CList}")
public Response addCLocation(#QueryParam("employeeId") String eId) throws SQLException{
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
PreparedStatement ps0 = null, ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try{
//Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
//Connection variables: dbPath, userName, password
con = (Connection)
DriverManager.getConnection(dbURL,"someusername","somepassword");
System.out.println("We are connected to database");
//SQL Statement to Execute
System.out.print(id);
s = con.prepareStatement("SELECT 1 FROM CList WHERE Number=?");
s.setString(1, eId);
rs = s.executeQuery();
//Parse SQL Response
if(!rs.next()) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) " +
"VALUES (?,?,?,?)");
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhone());
ps.executeUpdate();
ps = con.prepareStatement("SELECT Number, First_Name,
Last_Name, Phone_Number FROM CList
WHERE Number=" + eId);
rs1 = ps.executeQuery();
while(rs1.next()){
result = "[Added contact to contact list.
Number: " + rs1.getString(1) +
"][First_Name: " + rs1.getString(2) +
"][Last_name: " + rs1.getString(3) +
"][Phone_Number: " + rs1.getString(4) +
"]\n";
}
}
else {
result = "[Contact is already on the list]";
}
}
catch(Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
//Close Database Connection
ps0.close();
ps.close();
con.close();
}
}
catch(Exception e) {
System.out.println(e);
}
//Return the Result to Browser
return Response.status(1000).entity(result).build();
}
Table
1234 number is unique and it is a number I want to get.
You see number should be unique. So far I am taking data from the SMember class and it always insers the same data. Purpose of my question is just to ge the information I inserted few seconds ago.
Also, there is SMember class that I didn't post here and in its constructor I initialize number, first name, last name, and phone number. Testing purpose.
I made all recommended changes but problem remains the same.
There is several issues here.
The solution to your question is that you do not let the database generate keys, that is why you cannot ask for the generated keys later.
Look at this line of your code:
ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name, Phone_Number) VALUES ('"+sm.getEmployeeID()+"', '"+sm.getFirstName()+"', '"+sm.getLastName()+"', '"+sm.getPhone()+"')", Statement.RETURN_GENERATED_KEYS);
You later want to retrieve the Number column's value as a generated key. You however do pass a value for that column, namely the return value of sm.getEmployeeID(). If you pass a value, it will not get generated (assuming that this column is defined in database as being auto incremented.
Fixing this however, will not solve everything as your code has quite a lot of issues. Let me list the ones I can directly spot:
You initialize your variable sm by creating a new object. But you will still not have values for employee id, first name, last name or phone number as you nowhere set those values to sm (or do you do that in the default constructor?).
You are trying to use a prepared statement, this is good, but you are actually not doing that, this is very bad as it openes the ground for SQL injection. Instead of creating the query string like you are doing, you should use a fixed string like e.g INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?) and then set the values on the statement before executing it. That way nobody can mess with your database through that statement (read up on SQL injection, just google it to see the issue you would introduce).
Your employee id seems to be the eId parameter of your method. You should use that also in your select statement to see if it is already in your database (use a prepared statement here also) and in your insert statement later when the id is not already in the database.
If you are checking for a specific id, then insert that specific id, it is quite useless to retrieve some generated id. You already have defined your unique identifier. Use that one!
Edit: As your code is kind of a mess, I have cleaned this stuff a bit and fixed the issues that I could directly find. Check if this is helping you:
public Response addCLocation(String eId) throws SQLException {
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
Statement s = null;
PreparedStatement ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try {
// Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
// Connection variables: dbPath, userName, password
con = DriverManager.getConnection(dbURL, "someusername", "somepassword");
System.out.println("We are connected to database");
s = con.createStatement();
// SQL Statement to Execute
System.out.print(id);
PreparedStatement alreadyThere = con.prepareStatement("SELECT 1 FROM CList WHERE Number = ?");
alreadyThere.setString(1, eId);
System.out.println("0");
// Parse SQL Response
int i = 0;
if (rs.next() == false) {
SMember sm = new SMember();
ps = con
.prepareStatement("INSERT INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) VALUES (?,?,?,?)");
ps.setString(1, sm.getEmployeeID());
ps.setString(2, sm.getFirstName());
ps.setString(3, sm.getLastName());
ps.setString(4, sm.getPhone());
ps.executeUpdate();
}
else {
result = "[Contact is already on the list]";
}
}
catch (Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
// Close Database Connection
s.close();
ps.close();
con.close();
}
}
catch (Exception e) {
System.out.println(e);
}
// Return the Result to Browser
return Response.status(200).entity(result).build();
}
You are getting this error because your first query is wrong it is returning an empty resultset.
Firstly,
rs = s.executeQuery("SELECT 1 FROM CList WHERE Number='id'");
the above line in your code is not correct it should be like this:
**rs = s.executeQuery("SELECT 1 FROM CList WHERE Number="+id);**
then the correct query will be fired to database.
Secondly,there is problem in following code
if(rs.next() == false) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO CList (Number, First_Name, Last_Name,
Phone_Number) VALUES ('"+sm.getEmployeeID()+"',
'"+sm.getFirstName()+"', '"+sm.getLastName()+"',
'"+sm.getPhone()+"')",
Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
In the above code you should initialize the SMember, object currently in query they are going as null also the when you are using PreparedStatement you should use the query like this:
**ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhoneNumber());**
The Query statement maybe an issue "SELECT 1 FROM CList WHERE Number='id'",In select statement your id is taken as a String.we need to replace with value.
-->Try like this {"SELECT 1 FROM CList WHERE Number="+id},
-->One more thing "select 1 from table name" will print 1 for no of rows avail for your condition.
So my suggestion is
{"SELECT * FROM CList WHERE Number="+id}
try This!!
"SELECT 1 FROM CList WHERE Number='id'"
It looks like you're trying to actually select records where the Number value is 'id'. That may be causing the error when you try to do the "rs.next()" command on an empty result set. Are you instead trying to do something like
"SELECT 1 FROM CList WHERE Number=' " . id . "'"? Where "id" is a variable?