i'm want to store emails from Gmail into my mysql database.
i found Inboxreader with google but the part for connection to mysql is not working.
the username, database name, password is correct.
can anyone help me.
Thank you.
here is the part of the code
{
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("password");
String url = details.getProperty("jdbc:mysql://localhost/test");
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st= conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
{
try{
st.setString(1, mail);
st.execute();
}catch(Exception e){}
}
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
e.printStackTrace();
}
finally
Here is the error code:
Cannot connect to database server
java.sql.SQLException: The url cannot be null
Reading:23
at java.sql.DriverManager.getConnection(DriverManager.java:554)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at inboxreader.InboxReader.connecttoMySql(InboxReader.java:181)
at inboxreader.InboxReader.Start(InboxReader.java:82)
at inboxreader.InboxReader.main(InboxReader.java:34)
Thank you
This is your problem:
String url = details.getProperty("jdbc:mysql://localhost/test");
You are getting a null value in url. That's because there is no property called jdbc:mysql://localhost/test in your properties file.
You have two options. One would be using url directly with something like:
String url = "jdbc:mysql://localhost/test";
The other option would be having a correctly set up property in details.properties:
# hello, I am details.properties file
jdbc.url=jdbc:mysql://localhost/test
Then, in your Java code you would read url from property like this:
String url = details.getProperty("jdbc.url"); // note that we're changing property name
You're trying to get the value of a property from details like this:
String url = details.getProperty("jdbc:mysql://localhost/test");
It seems to me that the name of the property there is actually your value.
Thats because you don't have one key "jdbc:mysql://localhost/test" in your properties file. Let's say that details.properties have this content:
url=jdbc:mysql://localhost/test
So your code should be
String url = details.getProperty("url");
I am sure that your property key ha issue :
String url = details.getProperty("jdbc:mysql://localhost/test");
You should first validate that weather you have correct key or not
if (details.getProperty("jdbc:mysql://localhost/test") != null ||
details.getProperty("jdbc:mysql://localhost/test").trim().length > 0){
url =details.getProperty("jdbc:mysql://localhost/test");
}else{
return new Exception("Wrong property key");
}
Related
I am using the CData JDBC Driver for XML to read XML files to my java application and some of those files are on google drive so OAuth is needed.
I am following the Authenticate to XML from a Web Application flow specified on CData website.
The first step is to get the OAuth Authorization URL using the GetOAuthAuthorizationURL stored procedure.
Here is my code:
try {
Class.forName("cdata.jdbc.xml.XMLDriver");
} catch (ClassNotFoundException e1) {
}
String url="";
Properties prop = new Properties();
prop.setProperty("InitiateOAuth", "OFF");
prop.setProperty("OAuthClientId", "my-client-id");
prop.setProperty("OAuthClientSecret", "my-client-secret");
prop.setProperty("CallbackURL", redirectUri);
prop.setProperty("OAuthAuthorizationUrl", "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive.readonly");
try (Connection connection = DriverManager.getConnection("jdbc:xml:", prop)) {
CallableStatement cstmt = connection.prepareCall("GetOAuthAuthorizationURL");
boolean ret = cstmt.execute();
if (ret) {
ResultSet rs = cstmt.getResultSet();
while (rs.next()){
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
System.out.println(rs.getMetaData().getColumnName(i) + "=" + rs.getString(i));
if (StringUtils.equals(rs.getMetaData().getColumnName(i), "URL"))
url = rs.getString(i);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
The redirect_uri parameter from the url returned is always set to the default value [127.0.0.1] instead of the callbackURL I send as a property to the JDBC.
prop.setProperty("CallbackURL", redirectUri);
How can this be fixed
This was the way to do it:
cstmt.setString("CallbackURL", redirectUri);
I made a fairly small java program in netbeans, with the database saved in the scr folder under database/mainUserData, On my main pc, if i export it to a .jar folder, It works, If i copy all the data in the folder (70mb's worth) to another pc, it can't find the database any more, I made sure to add code that always uses the current directory in the jar folder as a url to the database, this is the connection code:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", "jacovanstryp", "Password1234");
Why is it when i move it to another computer (The whole file, it no longer knows where the database is?
What I have Tried:
URL url = this.getClass().getResource("/com/vanstryp/res/Database/MainUserData"); // This is the same directory as where the .jar is located
This just returns Null.
This is the top Error code it returns
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.
This is the code for the method I used
public boolean checkLogin(String username, String password) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//This code will connect the database to the java program
//Information to connect database obtained from --> https://www.youtube.com/watch?v=c7RZV4VLv3s
Connection myconObj = null; //allows to connect to database
Statement mystatObj = null; // create statement (Execute queries)
ResultSet myresObj = null; // get result
ResultSetMetaData mymeta = null;
try {
String query = "select * from JACOVANSTRYP.MAINUSERDATA";
URL databaseLocation = this.getClass().getResource("/com/vanstryp/database/MainUserData/");
myconObj = DriverManager.getConnection("jdbc:derby:/" + databaseLocation, "jacovanstryp", "Eduplex1234");
mystatObj = myconObj.createStatement();
myresObj = mystatObj.executeQuery(query);
mymeta = myresObj.getMetaData();
int colomnNo = mymeta.getColumnCount();
while (myresObj.next()) {
String dbUsername = myresObj.getString("Username");
String dbPassword = myresObj.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;
} catch
(ClassNotFoundException ex) {
Logger.getLogger(commonMethods.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
This line:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", ...);
uses a connection string of "jdbc:derby://localhost:1527/MainUserData". That means that you have setup (maybe through Netbeans) a Derby server on that computer listening on port 1527.
Copying a jar and the file backing the database is not enough: you must start the Derby server on the new host or use the one from the old host:
myconObj = DriverManager.getConnection("jdbc:derby://other.host.full.name:1527/MainUserData", ...);
Alternatively, you could use the embedded mode of Derby. Then you just have to declare which folder contains the database file:
myconObj = DriverManager.getConnection("jdbc:derby:/path/to/MainUserData", ...);
In this mode, you can just copy both the jar (and its optional other files) and the database to the new system, and it should find the database if you give a correct path.
I am trying to learn how you would tackle the task of creating a Java console application, connect to a (in this case) MySQL DB and send or retrieve data, without showing your username and password in the source code of the Java application. I currently have no trouble
creating a connection showing credentials.
// JDBC driver name and database URL
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://192.168.1.159:3306/javahelper";
// Database credentials
private static final String USER = "xxxx";
private static final String PASS = "RandomString";
/**
* #return
*/
public Connection openConnection() {
Connection connection = null;
try {
Class.forName(JDBC_DRIVER);
// opening connection
connection = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
System.out.println("This is from openConnection method");
e.printStackTrace();
} catch (SQLException f) {
System.out.println("This is from openConnection method");
f.printStackTrace();
}
return connection;
}
From what information I can gather you always need to show your credentials somewhere in the application. But how do you than achieve "safe" connection between a application and a DB, so others can't misuse your credentials for malicious reasons?
one way of doing it is using a properties file having your credentials or having your data in a xml file.
create a properties file like the one below
// database.properties
DB_URL=jdbc:mysql://localhost:3306/UserDB
DB_USERNAME=user_name
DB_PASSWORD=password
Use this information in your code to get the username and passwords.
Properties properties= new Properties();
FileInputStream input = null;
try{
input = new FileInputStream("database.properties");
props.load(input );
con = DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getProperty("DB_PASSWORD"));
}
you can use encrypt the username and password.The best opensource encryptor(My personal view) is jbcrypt
// Hash a password for the first time
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
// gensalt's log_rounds parameter determines the complexity
// the work factor is 2**log_rounds, and the default is 10
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));
// Check that an unencrypted password matches one that has
// previously been hashed
if (BCrypt.checkpw(candidate, hashed))
System.out.println("It matches");
else
System.out.println("It does not match");
Sharing what i find
Creating and using the propertise file
I created a database.properties file(normal text file) and placed it in the src folder of the Java project.
JDBC_DRIVER=com.mysql.jdbc.Driver
USER=YourUser
PASS=YourPassword
DB_URL=jdbc:mysql://IP:PORT/DB
Afterwards i edited my openConnection() method to use the properties file for loading the credientials of the connection.
public Connection openConnection() {
Properties properties = new Properties();
Connection connection = null;
String path = System.getProperty("user.dir");
path += "/src/database.properties";
try(FileInputStream fin = new FileInputStream(path);) {
properties.load(fin);
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// opening connection
connection = (Connection) DriverManager.getConnection(properties.getProperty("DB_URL"),properties.getProperty("USER"),properties.getProperty("PASS"));
} catch (ClassNotFoundException e) {
System.out.println("This is from openConnection method");
e.printStackTrace();
} catch (SQLException f) {
System.out.println("This is from openConnection method");
f.printStackTrace();
}
} catch (IOException io) {
System.out.println("This is from openConnection method");
io.printStackTrace();
}
return connection;
}
Sending username and password, Java application -> MySQL
From what i can read on the web, it dosent matter much if you encrypt or hash the password before you send it towards the sequel service from your Java application. An example i found is that the sequel service dosent have a "receive hash method and authenticate". And even if it did the hash would need to be in the program somewhere. And when the program has access to it, others also have access to it if they really want it. Also if the hash is whats needed to authenticate than your back to where you can just as well use the clear text password.
The discussion than ends on "what is the best approach". Some suggest a keyserver / auth system in between the application and sequel service, using a datastore setup on the server side, using the OS "wallet" (example Windows registry) or creating a database user with minimum permissions to just get the job done / or a read only DB "read_only=1 in my.cnf".
I tried the 3'rd option and created a "DBaccess" user, with only the select permission to retrieve data, no administrative rights and random generated password by MySQL.
I'm using the tutorial at http://www.vogella.com/tutorials/MySQLJava/article.html
to try tp connect to my sql server on my server
When it executes the line:
Connection connect = DriverManager
.getConnection("jdbc:mysql:http://www.findmeontheweb.biz"
+ "user=findmeon_bitcoin&password=PASSWORD");
an exception gets thrown saying "No sutabled driver found for jdbc:mysql:http://www.findmeontheweb.biz
This is what I did
1. Downloaded the "mysql-connecter-java-5.1.33.bin.jar into my lib folder
2. added the jar to my project from preferences.
project code:
public class cStart {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main (String[] args) {
int g=0;
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.
// EXCEPTION GOES OF HEAR
Connection connect = DriverManager
.getConnection("jdbc:mysql:http://www.findmeontheweb.biz"
+ "user=findmeon_bitcoin&password=PASSWORD");
} catch (Exception e) {
System.out.println("Exception...." );
}
}
}
The URL format should be look like this
jdbc:mysql://hostname/ databaseName
I think this is a much cleaner way to do it:
String URL = "jdbc:URL_TO_YOUR_DATBASE";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
As seen here: http://www.tutorialspoint.com/jdbc/jdbc-db-connections.htm
I say give that link a try with your driver. You also should make sure you have the actual jar for MySQL. It really might be invalid.
I would try the one here: http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
And then add that to your project.
The URL to the database might be wrong.
If yes you should specify a correct one with including database name.
Else verify if the jdbc driver jar is added in the build-path, if yes try to put it in the lib folder of your webapp.
I am trying to connect to mssql server from java but I couldnt figure it out. It throws an exception
ERROR: No suitable driver found for jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MLS_J
here is the code below. What am I doing wrong? How can I fix this?
public static String connection_test(){
String address = "jdbc:sqlserver://192.168.1.101:1433;DatabaseName=MLS_J";
String user = "sa";
String password = "xxxx";
try {
Connection conn = DriverManager.getConnection(address, user, password);
java.sql.Statement stmt = conn.createStatement();
return "Bağlantı kapalımı? - " + conn.isClosed();
} catch (Exception e) {
return "ERROR: " + e.getMessage();
}
}
You might wanna take a look at this.
Try adding this line to your code:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Follow the steps for adding jar files in build path
Right click on project
click build path-> configure build path
click libraries folder
then click add external jar and give the path of the sqljdbc4.jar.
I would suggest you to use jtds driver.