Sunday, January 13, 2013

Java Mysql Connection

                          JAVA MYSQL CONNECTION
If you want to develope a program that uses database as mysql you should connect to the mysql. There are some methods of connecting to the database one of them that i will mention is using connector jar.

In J2EE project structure, there is a folder named as libs under the WEB-INF folder which is under your Webapps or WebContent or any of named folder that puts your all user interface files such as jsps, htmls... The lib folder is special for the J2EE development because it holds all the 3rd party jars. So one way is to put your connector jar to there. Just copy your jar into the libs folder thats easy. The connector jar is for the mysql http://dev.mysql.com/downloads/connector/j/

Then lets come to our java file that can be servlet or jsp or bean etc... Of course Jsp is not a good choice :)) Lets come and open a class that will contain our db operations.

lets code a one function that creates a connection

public static Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;

try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/canuysal","root", "yourpassword");

} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}

This will return your connection


connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/canuysal","root", "yourpassword");
In this function
/localhost:3306/ this is your address and port where the db installed.
"root" this is your user
"yourpassword" this is your password

1 ) Lets insert into table and query the record.


ResultSet insertId = null;
String record= "0";
Connection connection = getConnection();
if (connection != null) {
Statement st = connection.createStatement();
 int val = st.executeUpdate("INSERT TABLES(X,Y,Z) VALUES('x','y','z')");
 Statement st2 = connection.createStatement();
 insertId = st2.executeQuery("SELECT gameId from TABLES WHERE X='x'");
 while (insertId.next()) {
record= insertId.getString("X");
}
} else {
System.out.println("Connection Fails!!!!");
}
connection.close();

2 ) Lets delete now
Statement st2 = connection.createStatement();

int val = st2.executeUpdate("DELETE FROM TABLES WHERE X = 'x'");

that if you put this code the field will be deleted from the table.





No comments:

Post a Comment