I'm using properties file for Database,and here is mycode:
And I have set my database.prperties file in straight src folder.
here is my code(I'm applying this code in a jsp page):
Properties prop=new Properties();
InputStream inputStream=null;
try{
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties");
prop.load(inputStream);
}
finally{
if (inputStream != null) try { inputStream.close(); } catch (IOException ignore) {}
}
String driver=prop.getProperty("driver");
if (driver != null)
{
System.setProperty("driver", driver);
}
String url = prop.getProperty("url");
String username= prop.getProperty("username");
String password = prop.getProperty("password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,username,password); // Getting error at this line.
Statement stmt = con.createStatement();
String sql = "select * from info;";
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
Here is my properties file :
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/abc
username=crips
password=drift
But I'm getting this error java.sql.SQLException: Access denied for user 'root '#'localhost' (using password: YES) at line Connection con = DriverManager.getConnection(url,username,password);
Any inputs on this context will appreciated.
java.sql.SQLException: Access denied for user 'crips'#'localhost'
This means that the given user isn't been granted access to the database which you're attempting to connect. You'd need to issue the following SQL command with MySQL admin rights:
GRANT ALL ON abc.* TO 'crips'#'localhost' IDENTIFIED BY 'drift';
Note that the user name and password are case sensitive.
Also note that this has after all nothing to do with reading properties files. You'd have exactly the same problem when supplying username/password/database as hardcoded string variables.
Related
I am making an FXML application with intelliJ and MYSQL in Java 11 that allows the user to create a database that has a name of their own choosing. The application:
recognises that the database doesn't yet exist
creates the database via a connect string that uses URL without a specfic DB name
connects to the new database and executes an sql.txt file thereby creating all the required tables.
This approach works save for the fact that when the final statement of the code below executes an automated alert pops up with:
"Cannot connect to database. Please close the program, check the driver is available and that the connection details are correct and then try logging on again".
It does this even though the new database with all required tables has been created and connected to.
Question: Is there anyway to disable this auto-generated message?
protected void execute() throws Exception {
// Connect using URL without DBNAME:This is a re-assignment of inherited value
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Create database at user request:
String sql = "CREATE DATABASE " + this.newDBName;
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
StringBuilder sqlText = new StringBuilder();
File file = new File(this.getClass().getResource("createSQLScript.txt").toURI());
/*
Read in the Sql statement text file resource to create tables
using try-with resources and automatic resource closure.*/
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
sqlText.append(line);
}
}
// Set connection object to allow multiple queries in createSQLScript.txt
// A re-assignment of inherited value
conn = DriverManager.getConnection(DB_URL + this.newDBName + "?allowMultiQueries=true", USER, PASS);
stmt = conn.prepareStatement(sqlText.toString());
stmt.executeUpdate(sqlText.toString());
}
PS: DB_URL is - jdbc:mysql://localhost:3306/
This could be related to the fact that you created database in one connection and started accessing it in another connection without closing the previous one.
Connection and PreparedStatement are closable resources. You should always close them with try-finally or try-with-resources pattern, e.g.:
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
// execute stmt...
// populate database...
}
}
try (Connection conn = DriverManager.getConnection(
DB_URL + this.newDBName + "?allowMultiQueries=true", USER, PASS) {
// access newly created database...
}
I have no idea what wrong is with my sample code, I've followed all instructions on multiple YouTube videos and other online sources. I just can't fix it. Could someone explain what is the problem and how to solve it? All the required lib's are already added.
I have made sure all the libraries are correctly installed, Yet it still does not find the driver.
This is my code
public boolean checkLogin(String username, String password) {
try {
Connection myconObj;
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
URL databaseLocation = this.getClass().getResource("/com/vanstryp/database/MainUserData.accdb");
myconObj = DriverManager.getConnection("jdbc:ucanaccess:/" + databaseLocation);
ResultSet result;
Statement stmt = conn.createStatement();
String query = "select * from MainUserData";
result = stmt.executeQuery(query);
while (result.next()) {
String dbUsername = result.getString("Username");
String dbPassword = result.getString("Password");
System.out.println();
if (username.equalsIgnoreCase(dbUsername) && password.equals(dbPassword)) {
PrintWriter activeUser = new PrintWriter(new FileWriter("activeUser.db"));
activeUser.println(dbUsername);
activeUser.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
This is the error message:
java.sql.SQLException: No suitable driver found for jdbc:ucanaccess:/file:/C:/Users/Jaco%20van%20Stryp/Dropbox/Fitness%20Perfect/build/classes/com/vanstryp/database/MainUserData.accdb
java.sql.SQLException: No suitable driver found for jdbc:ucanaccess:/file:/C:/Users/Jaco%20van%20Stryp/Dropbox/Fitness%20Perfect/build/classes/com/vanstryp/database/MainUserData.accdb
A UCanAccess connection URL must begin with jdbc:ucanaccess:// followed by the path to the database file. Your connection URL begins with jdbc:ucanaccess:/ (only one slash) and it also includes the spurious file: designator. It should look more like this:
jdbc:ucanaccess://C:/path/to/database/file.accdb
I want to access MySQL database within my MapReduce program. I have a DBConnection class and I getConnection within the mapper class.The db.properties file is in place and with correct path mentioned in the DBConnection class.
Everytime I run the hadoop jar command I get error java.io.FileNotFoundException: db.properties (No such file or directory).
How can I resolve this?
Establishing DB connection in mapper:
Connection con = DBConnection.getConnection();
PreparedStatement pst = null;
String selectRows = "Select count(*) from sample";
Thanks
Try with this:
Prior Java 1.7:
InputStream input = YourClassName.class.getResourceAsStream("/db.properties");
try {
prop.load(input);
} catch (IOException ex) {
}finally{
input.close();
}
Java 1.7 and ahead:
try (InputStream input = YourClassName.class.getResourceAsStream("/db.properties")) {
prop.load(input);
} catch (IOException ex) {
}
I am using the JDBC driver to connect to a mysql database and using the "LOAD DATA INFILE" command in my java application to load(insert) a text file into the database. I am getting the following error: Data truncation: Data too long for column xxx at row 1.
However if I load the same text file manually by logging into the database and entering the SQL manually, the data loads fine.
Can someone pelase tell me what the error might be?
I am running this on Red Hat Enterprise Linux Server release 5.8 and the jdk version is 1.5.0_16 if that helps
This is the function used to load the data
public static void loaddata(Connection conn, String filename, String tablename)
{
try{
Statement stmt = null;
stmt = conn.createStatement();
File file = new File(filename);
file.getAbsolutePath().replace("\\", "\\\\");
String cmd = "LOAD DATA INFILE '"
+ file.getAbsolutePath().replace("\\", "\\\\")
+ "' INTO TABLE " + tablename + " FIELDS TERMINATED BY \'^\'";
stmt.executeUpdate(cmd);
System.out.println("cmd :" + cmd);
}
catch(SQLException sqle){
sqle.printStackTrace();
}
}
This is the function to create the JDBC connection:
public static Connection createConnection()
{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e) {
e.printStackTrace();
}
try {
String url = ""; //URL mentioned in the actual code
conn = DriverManager.getConnection(url, user, pass);
} catch (SQLException sqe1) {
sqe1.printStackTrace();
}
return conn;
}
Does anyone have any ideas of how to connect Access 2010 to java jdbc. I use this method, but when I call it, it doesn't work:
public void loadDb(){
try{
Class.forName("sun.jdbc.JdbcOdbcDriver");
File f = new File(System.getProperty("user.dir"))
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Acess Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
st = con. createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
}catch(ClassNotFoundException e){e.printStackTrace();
}catch(SQLException e){e.printStackTrace();}
}
//con and st are already defined
According to msdn it should be sun.jdbc.odbc.JdbcOdbcDriver. So replace this line of code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Spelling error? Perhaps this line:
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Acess Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
should be
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
Access has 2 C's
Create connection
public static Connection getConnection() {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:anime"; //anime is the database
String username = "ipieluser"; //leave blank if none
String password = "ipielpassword"; //leave blank if none
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
How to call:
public static void main(String args[]) {
try {
Connection conn = getConnection();
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM localTable");
//get and displays the number of columns
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
st.close();
conn.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
Use UCanAccess JDBC Driver :
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); // can be omitted in most cases
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<mdb or accdb file path>",user, password);
e.g.:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/pippo.mdb");
So for your example it will be
con = DriverManager.getConnection("jdbc:ucanaccess://"+f.getPath()+"/db/JavaAccess.accd")
Rishab's reply helped me to connect to my access database.
I did following correction in the code:
Instead of
String url = "jdbc:odbc:anime"; //anime is the database
I did
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" + "d://institute//institutedata.accdb";
I explicitly defined driver and full database name with path and extension.
As today only we face the same problem and found that to check the version of java if your
version of java if the version of the java is above 7 then the sun.jdbc.odbc.JdbcOdbcDriver will not be supported so just check the version of the java.