Download the file, get the jar and import that to your current project.
Prepare your mysql db, create a new database named 'testdb', make a table 'mytable', make some column, insert some data. Or if you want to work with some existing database,tables etc, that will also be fine.
After mysql preparation completed and database server is running, open a java file for testing, write the following lines:
Connection conn = null;
try{
String userName = "username";
String password = "passsword";
String url = "jdbc:mysql:portnumber//localhost/databasename";
//here we are using the library
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e){
System.err.println ("Couldn't connect to mysql database");
}
now we have completed connecting. Also don't forget to close the connection at the end of your code.
Here is some example code for manipulating your db from java:
if (conn != null){
try{
String id="id";
String val="value";
PreparedStatement ps;
ps = conn.prepareStatement("INSERT INTO animal (name, category) VALUES(?,?)");
ps.setString (1, id);
ps.setString (2, val);
int count = ps.executeUpdate ();
}
catch (Exception e){
//if you need to do something upon error
}
finally{
conn.close ();
System.out.println ("Database connection closed");
}
}
You can also use this for connecting to other databases, just use different connection library for each.










2 comments:
Hi rana im having a doubt in Mysql.
Select from where in (select from )
Inquery gives me the value like (234,456..) when i running out seperately.
but when i combine this above query its not executing.but it runs well if i give like
Select from where in (234,456..))
can u help me why the query is not executing in the case of subquery
Can you please give a example query your trying with? Try with the following format:
"SELECT name, email FROM tbl_contact WHERE name IN(SELECT name from tbl_User)"
like this. Its working good for me...
Post a Comment