I m trying to execute this code & it shows successfull execution but i cant get any value n access database file which i had create.
so, please find mistake in my code so that i can get some values in database table.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename ="D:\\Database for Mini Project\\Database21(example).mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database for Mini Project\\Database21(example).mdb";
try (Connection con = DriverManager.getConnection( database ,"","")) {
Statement s = con.createStatement();
String b=request.getParameter("uname");
String c=request.getParameter("pass");
String query="insert into A.ABC1(uname,pass) values='"+b+"','"+c+"'";
s.executeQuery(query);
s.close();
change s.executeQuery(query); to s.executeUpdate(query);
For data manipulation language use executeQuery(); as mentioned in oracle docs
Try this
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename ="D:\\Database for Mini Project\\Database21(example).mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database for Mini Project\\Database21(example).mdb";
String b=request.getParameter("uname");
String c=request.getParameter("pass");
try {
// connects to the database
Connection con = DriverManager.getConnection( database ,"","")) {
Statement s = con.createStatement();
String query="insert into A.ABC1(uname,pass) values(?,?);
PreparedStatement statement = conn.prepareStatement(query);
s.setString(1, b);
s.setString(2, c);
int row = s.executeUpdate();
if (row > 0) {
message = "Query executed";
}
} catch (SQLException ex) { //catch ur msaccess exception..I use mysql
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (con != null) {
// closes the database connection
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
I use mysql as my database..so wherever there is catch(SQLException ex) replace it with msaccess exception..
Related
I have tried to use another proyect and the connection is succesfull but from this proyect I am only able to connect to localhost mysql. I want it to work only on lan.
I am getting "Access denied for user 'root'#'192.168.1.70' (using password: YES)"
Code sample from not working proyect:
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{ con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
st = (Statement) con.createStatement();
String s = "SELECT * FROM meta";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
while(rs.next()){
int meta = rs.getInt("meta");
goal.setText(Integer.toString(meta));
}
}catch(Exception e){}
finally{
try{ st.close();
rs.close();
con.close();
}
catch(Exception e){ JOptionPane.showMessageDialog(null, "InformaciĆ³n no encontrada");
}
}
Code sample from another proyect which connects succesfully
try
{
// create our mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://192.168.1.66:3306/jjeventoscore";
Class.forName(myDriver);
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM client";
// create the java statement
Statement st = (Statement) conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next()){
String name = rs.getString("name");
String last = rs.getString("last");
String h_phone = rs.getString("h_phone");
String m_phone = rs.getString("m_phone");
String of_phone = rs.getString("of_phone");
String ex_phone = rs.getString("ex_phone");
String email = rs.getString("email");
String medium = rs.getString("medium");
System.out.println(name+" "+last);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
You need to give privileges to the user on that Database and that Table.
With privileges, on your MySQL instance:
USE jjeventoscore;
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70';
Or maybe try
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70' IDENTIFIED BY '';
Since it says "Using password: YES"
Also, check the password on MySQL. It should match the parameter in this function
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
I am using Mysql netbeans . I have created a db table "userdetails_summertrainingproject" . In the login form I have two fileds to fill one is "UUId_JTextField" and other is "Password1_JPasswordField". I want to compare that the password value entered by the user is same as that in db for the particular UUId entered by the user. UUid is unique.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = new String(password1);
if(rs.getString(query)==pass1){
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
}
catch(Exception e){
System.out.println("Exception in Login:"+e.getMessage());
}
Above is the code I am using.
The Exception is:
Exception in Login:Column 'SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;' not found.
Try this code, you missed rs.next()
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = Arrays.toString(password1);
rs.next();
if (rs.getString("password").equals(pass1)) {
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
I think it is batter to use another method for get connection string. otherwise you have to write bellow code again and again.
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
EDIT:
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
String query = "SELECT UUId FROM userdetails_summertrainingproject;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
String UUId = rs.getString("UUId");
System.out.println("UUId " + UUId);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class and add this code. then check this code is working or not.
please make sure port, database name, user and password is correct.
If this is give com.mysql.jdbc.CommunicationsException: Communications link failure. most probably your port is incorrect.
I am use these two libraries.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query="SELECT password FROM tryingtable WHERE name=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
prepstmt.setString(1,jtf.getText());
ResultSet rs=prepstmt.executeQuery();
rs.next();
String result=rs.getString("password");;
char[] pass = jpf.getPassword();
String password1= new String(pass);
if(result.equals(password1))
JOptionPane.showMessageDialog(null, "go!!");
else
JOptionPane.showMessageDialog(null, "no!!");
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
e.getStackTrace();
}
when you want to compare password field to textfield use
char[] pass_char = passwordField.getPassword();
String pass_string = new String(pass_char);
Above code will give you your password field value in string form, then
if(pass_string.equals(textfield))
JOptionPane.showMessageDialog("Password match");
else
JOptionPane.showMessageDialog("Password did not match");
I want to insert a row in a table in Oracle SQL Developer. I have a set of Strings, String name, String address, and String contact.
It won't work if I use this code:
Connection conn = null;
Statement stmt = null;
String URL = "jdbc:oracle:thin:mariel#//localhost:1521/XEXDB";
String USER = "mariel";
String PASS = "1234";
String name = "a", address = "a", contact="a";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
conn = DriverManager.getConnection(URL, USER, PASS);
stmt = conn.createStatement();
String sql = "INSERT INTO CUSTOMER" +
"VALUES(CustNumSeq.NEXTVAL, name, address, contact)";
stmt.executeUpdate(sql);
}
catch (SQLException ex) {
Logger.getLogger(FinishTransaction.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
finally{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
modify your code as below
String sql = "INSERT INTO CUSTOMER " +
"VALUES(CustNumSeq.NEXTVAL, name, address, contact)"
you must keep a space between table name(CUSTOMER) and VALUES
As per modified post
String sql = "INSERT INTO CUSTOMER " +
"VALUES('"+ name+"','"+ address+"','" +contact+"')"
Note: You should always prefer to use PreparedStatement than Statement as
PreparedStatement is having much advantages than Statement.Please see the link for more info
I've got a following problem: I'm trying to insert data (in this case a username) into a table using the following code:
void AddNewUser(String name, Connection conn){
if(ret == null){
ret = new DB_Retriever(conn);
}
if(!ret.UserExists(name, conn)){
try{
Statement stm = conn.createStatement();
stm.executeUpdate(DB_OperationalData.insert_new_user[0][0] + name + DB_OperationalData.insert_new_user[0][1]);
stm.executeUpdate(DB_OperationalData.insert_new_user[1][0] + name + DB_OperationalData.insert_new_user[1][1]);
stm.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
By the way: It absolutely doesn't matter what I put in the catch clause, nothing that I put there is executed. Just to make everything clear, here is the content of the DB_OperationalData.insert_new_user String array:
public static final String[][] insert_new_user = {
{"INSERT INTO User (Username, Status) VALUES ('","','IN');"},
{"INSERT INTO Statistics (Player_ID) SELECT ID FROM User WHERE Username='","';"}};
The second statement is supposed to copy the ID of the user that is inserted and put it into Player_ID field of the Statistics table (Table User's ID is an autonumbered field).
The exception I get is:
Error while processing the query: java.sql.SQLException: ResultSet closed
What is interesting, is that it works and the data is added correctly but I simply do not want any exceptions thrown.
That's the console output I get:
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
All the lines above the Exception are my own printouts, so I know what has actually happened.
[EDIT]
I have changed the code to use the PreparedStatement instead of ordinary Statement and the current try clause looks as follows:
PreparedStatement pstm = conn.prepareStatement(DB_OperationalData.insert_new_user[0]);
pstm.setString(1, name);
pstm.addBatch();
conn.setAutoCommit(false);
pstm.executeBatch();
conn.setAutoCommit(true);
pstm.close();
And the output is (still regardless of the contents of the catch clause):
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at org.sqlite.PrepStmt.batch(PrepStmt.java:173)
at org.sqlite.PrepStmt.setString(PrepStmt.java:254)
at data.DB_Writer.AddNewUser(DB_Writer.java:28)
at data.DataHandler.AddNewUser(DataHandler.java:94)
at data.Tester.main(Tester.java:18)
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
[EDIT 2]
With regards to the original version, when I remove the stm.close(); there is absolutely no difference and I still get the 'ResultSet closed' Exception.
[EDIT 3]
Here is the code of the method that is calling the above:
public void AddNewUser(String username)throws IllegalUsernameException{
if(username.length()==0 || username.length()>20){
throw new IllegalUsernameException();
}
writer.AddNewUser(username, conn);
}
The connection to the database is established by this class:
class DB_Connection {
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName("org.sqlite.JDBC");
}
catch(ClassNotFoundException e){
log("Error while loading the database driver: " + e);
return null;
}
try{
conn = DriverManager.getConnection("jdbc:sqlite:database.db");
}
catch(SQLException e){
log("Unable to connect to the database: " + e);
return null;
}
return conn;
}
public static void log(String msg){
System.out.println(msg);
}
}
The DB_Retriever's method that is checking for the existing username:
boolean UserExists(String name, Connection conn){
String result = "";
try{
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(DB_OperationalData.user_exists[0] + name + DB_OperationalData.user_exists[1]);
result = rs.getString("Username");
}
catch(SQLException e){
System.out.println("Error while processing the query: " + e);
}
if(result.equals(name)){
return true;
}
return false;
}
The only location where Error while processing the query: java.sql.SQLException: ResultSet closed could be printed to the console is in UserExists(..), unless there is another method with a similar catch block. Indeed the ResultSet is not used correctly in UserExists, what may cause the error.
For a more complete description of how to work with JDBC look at this answer or the JDBC documentation. A possible alternative to the existing UserExists is:
boolean userExists(String name, Connection conn) {
PreparedStatement stmt = null;
try{
stmt = conn.prepareStatement("SELECT COUNT(Username) FROM User WHERE Username = ?");
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
rs.next(); // set cursor to first row
int count = rs.getInt(1);
rs.close();
return count > 0;
} catch(SQLException e) {
// propagate error
throw new RuntimeException(e);
} finally {
// clean up resources
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ignore) {
log("error on sql clean up", ignore);
}
}
}
}
I have a big question...
I have a database java program creation.
I want to know if the database exists or not, and the if exists just connect, if not to create it.
I tried this one:
if (dbName.exists() == false) {}
THIS IS ALL THE CODE...
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");
THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW....
PARTIAL CODE THAT WORKS !
conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);
System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);
BUT I WANT SOMETHING LIKE:
FILE dbName = new FILE (url);
Statement stmt = new Statement;
if (dbName.exists() == true)
System.out.println("Database exists ! Connecting ... ");
else {
String sql = "CREATE DATABASE "+url;
stmt.executeUpdate (sql);
}
I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.
So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ...
AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.
It is not working.... not entering in the else more, and says that Exeption Database already exists.
Thanks you very much.
If it is a MySQL database, the following code should work. Other databases may give a different error code, but the general way should be clear. Important is that you connect to the instance, not a specific database initially. For creating the tables, you will need to connect to the newly created database. You can't use the instance connection that I use in my example for creating the tables:
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/",
"root", "admin");
statement = connection.createStatement();
String sql = "CREATE DATABASE DBNAME";
//To delete database: sql = "DROP DATABASE DBNAME";
statement.executeUpdate(sql);
System.out.println("Database created!");
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
} catch (ClassNotFoundException e) {
// No driver class found!
}
// close statement & connection
Without knowing much about what's going on here simply trying to connect to a database that doesn't exists should throw a TimeoutException error or something similar. Just catch the exception and do stuff if you cannot connect.
boolean canConnect = false;
Connection conn = null;
try{
conn = DriverManager.getConnection(...);
canConnect = true;
}(Exception ex){
canConnect = false;
}
if (!canConnect){
makeDatabase(...);
}
Enjoy your day!
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
Statement statement = connection.createStatement();
String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
statement.executeUpdate(sql);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly Note a Two things
The new driver class is `com.mysql.cj.jdbc.Driver'
The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits