java with ms access not showing database result - java

I'm trying to connect with MS-Access using java but When I Compile this code it gives me no error and compile fine but it doesn't show any result while the database has records in it, table name and field name are also correct, anyone can please help me that what I'm doing wrong in it.
import java.sql.*;
public class database{
Connection dbCon;
Statement statement;
ResultSet result;
public database(){
connect();
}
public void connect(){
try{
String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(Driver);
String Sdb = "jdbc:odbc:students";
dbCon = DriverManager.getConnection(Sdb);
statement = dbCon.createStatement();
String sqlQuery = "SELECT * FROM StudentInfo";
result = statement.executeQuery(sqlQuery);
while(result.next()) {
//String name = result.getString("Studentname");
System.out.println(result.getString("Studentname"));
}
}catch(Exception ex){
}
}
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
new database();
}
}

You are not getting error during execution of program because you are eating exception here:
catch(Exception ex){
}
You should try to print the exception trace to know what is going wrong.
catch(Exception ex){
ex.printStackTrace();
}

Related

How to update column values in the table?

What is the problem in this code? where it is update the all column values with the same last one .
public class dbconnection {
java.sql.Connection con;
java.sql.Statement st;
ResultSet rs;
public EncBean getConnection()throws SQLException{
EncBean encBean1 = new EncBean();
String v_url= "jdbc:oracle:thin:#192.168.2.138:1522:orcl2";
String v_username= "scott";
String v_password = "tiger";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(v_url,v_username,v_password);
System.out.println ("Connection to Oracle database was Established");
}
catch ( SQLException e)
{
e.printStackTrace();
}
return encBean1;
}
public EncBean selectRows()
{
EncBean encBean2 = new EncBean();
try
{
String SQLselect="select JOB_NAME from job";
st=con.createStatement();
rs=st.executeQuery(SQLselect);
while (rs.next()) {
encBean2.setName(rs.getString("JOB_NAME"));
}
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return encBean2;
}
public void updateRows(String updatedname){
try
{
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
ResultSet srs = stmt.executeQuery("select job_name from job " );
while (srs.next()) {
srs.updateString("job_name", updatedname);
srs.updateRow();
con.commit();}
System.out.println("An existing user was updated successfully!");}
catch(SQLException err){
System.out.println(err.getMessage());
}}}
This is the main
public class mainenc {
public static void main(String[] args) throws Exception{
dbconnection dbcon = new dbconnection();
EncBean encbeancon= dbcon.getConnection();
EncBean encBean5 = dbcon.selectRows();
enc concatinputs = new enc();
EncBean encBeanconcat = concatinputs.funconcat(encBean5.getName());
EncBean encBean4 = concatinputs.inputencryption(encBeanconcat.getConcatenatedData());
String vReserverbin= encBean4.getReversedBinary();
String ascistring= concatinputs.convertBinaryStringToString(vReserverbin);
dbcon.updateRows(ascistring);
}}
What is the problem in this code? where it is update the all column values with the same last one .
After updated method you should write list method again.
Try to take this example:
UPDATE tableB
SET tableB.value , tableA.value, tableB.value)
WHERE tableA.name = 'Joe'
It is kind of obvious: dbcon.updateRows(...) calls for the update method and that method does the job.
But as Erhan said, you don't get to see the result because you don't actually make use of updated records, e.g. show them etc. At least, you can check it out at the DB level if op is completed.
But I really disliked your comment:
plz can you do it for me?
You should do your own task and ask help when you need a hand. But never expect someone else to do your job mate.

Error S1000 trying to execute more MySql queries in a Java Application

I have a problem trying to execute more than one query into my Java Application code.
I have a procedure that is called in main and is in the class "Fant":
public void XXX(){
Connectivity con=new Connectivity(); // this class set up the data for the connection to db; if ( !con.connect() ) {
System.out.println("Error during connection.");
System.out.println( con.getError() );
System.exit(0);
}
ArrayList<User> blabla=new ArrayList<User>();
blabla=this.getAllUsers(con);
for (User u:blabla)
{
try {
Connectivity coni=new Connectivity();//start a new connection each time that i perform a query
Statement t;
t = coni.getDb().createStatement();
String query = "Select count(*) as rowcount from berebe.baraba";
ResultSet rs = t.executeQuery(query);
int numPrenotazioni=rs.getInt("rowcount");
rs.close(); //close resultset
t.close(); //close statement
coni.getDb().close(); //close connection
}
}
catch (SQLException e)
{
System.err.println("SQLState: " +
((SQLException)e).getSQLState());
System.err.println("Error Code: " +
((SQLException)e).getErrorCode());
}
}
}
The called function is defined as:
ArrayList<User> getAllUsers(Connectivity con) {
try{
ArrayList<User> userArrayList=new ArrayList<User>();
String query = "Select idUser,bubu,lala,sisi,gogo,gg from berebe.sasasa";
Statement t;
t = con.getDb().createStatement();
ResultSet rs = t.executeQuery(query);
while (rs.next())
{
User utente=new User(....); //user fields got from query
userArrayList.add(utente);
}
rs.close();
t.close();
con.disconnect(); //disconnect the connection
return userArrayList;
} catch (SQLException e) {
}
return null;
}
The main is:
public static void main(String[] argv) {
ArrayList<User> users=new ArrayList<User>();
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Fant style = new Fant();
style.XXX();
}
The query performed into "getAllusers" is executed and into the arraylist "blabla" there are several users; the problem is that the second query that needs the count is never executed.
The MYSQlState given when running is= "S1000" and the SQLERROR is "0".
Probably i'm mistaking on connections issues but i'm not familiar with statements,connections,resultsets.
Thank you.
You might forget to call rs.next() before getting the result form it in XXX()methods as shown below:
ResultSet rs = t.executeQuery(query);
// call rs.next() first here
int numPrenotazioni=rs.getInt("rowcount");

Adding a new record in Access

I had this working at one point, but changed the path along with some other fields and now I just cant seem to get it updating again. Here is the code:
public class DbUpdate{
ResultSet rs;
Statement st;
public void DbUpdate(){
Connect();
}
public void Connect(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\User\\ugt\\Desktop\\ResourcePlanningTool_DB.accdb");
st = con.createStatement();
st.executeUpdate("INSERT INTO AssignmentDetails (Name) VALUES('Bob Joll')");
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args){
DbUpdate x = new DbUpdate();
}
}
At the moment the project runs without errors, but it doesn't seem to actually update the table. Also the path name is correct.
The public void DbUpdate() isn't quite a constructor and wasn't called. I removed the void and also added a con.commit() after the executeUpdate and it worked.
Edit: The commit doesn't seem to be needed.
int retVal = st.executeUpdate("INSERT INTO AssignmentDetails (Name) VALUES('Bob Joll')");
System.out.println("Inserted: " + retVal);
//con.commit();
//con.close();

I am unable to make an SQL query in Java

My code is-
package textmessenger;
import java.sql.*;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
try {
String con = "jdbc:mysql://SQL09.FREEMYSQL.NET:3306/a5189576";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
int updateQuery = 0;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(con, "user", "pwd");
statement = connection.createStatement();
String QueryString = "select * from names";
rs = statement.executeQuery(QueryString);
System.out.println("Executed");
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I run this program, I get "Error" in the output. Where am I going wrong?
I have tried the SQL editor in NetBeans and it works perfectly fine there.
Thanks in advance :)
From the stacktrace you've now posted, You need to download the MySQL JDBC driver and include it in your project:
http://dev.mysql.com/downloads/connector/j/

why can't java see my mysql driver

I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
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("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

Categories