First create database named "tryout" in MySQL:
- mysql> create database tryout;
- mysql> use tryout;
And create the table "user":
- mysql> create table `user`(
- -> `user_name` varchar(100) NOT NULL,
- -> `address` varchar(200) DEFAULT NULL,
- -> `first_name` varchar(50) NOT NULL,
- -> `last_name` varchar(50) DEFAULT NULL,
- -> `middle_name` varchar(50) DEFAULT NULL,
- -> PRIMARY KEY (`user_name`));
- mysql> INSERT INTO `user` VALUES('crazenezz', NULL, 'craze', NULL, NULL);
If we using Standard JDBC we will see this kind of code to get all the user.
- import com.mysql.jdbc.Connection;
- import com.mysql.jdbc.Statement;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class SimpleDBConnection {
- public static void main(String[] args) {
- try {
- Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/tryout", "root", "root");
- Statement state = (Statement) conn.createStatement();
- ResultSet rSet = state.executeQuery("SELECT * FROM user");
- while(rSet.next()) {
- System.out.println("Username: " + rSet.getString("user_name"));
- System.out.println("First Name: " + rSet.getString("first_name"));
- }
- } catch (SQLException ex) { Logger.getLogger(SimpleDBConnection.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
And let see if we use the CrzDB:
- import java.util.Map;
- import org.crz.db.config.Config;
- import org.crz.db.config.abs.impl.MySQLConfig;
- import org.crz.db.query.SQLQuery;
- public class CustomDBConnection {
- public static void main(String[] args) {
- Config config = new Config(MySQLConfig.getInstance("tryout"));
- SQLQuery query = new SQLQuery(config.getState(), "user");
- List<Map> datas = query.getAll();
- for(Map data : datas) {
- System.out.println("Username: " + data.get("user_name"));
- System.out.println("First Name: " + data.get("first_name"));
- }
- config.closeConnection();
- }
- }
If you more interested about this library you can check it out from here. and you can see another example in here.
I'm using:
- Netbeans 7.1.1 as IDE
- JDK 1.7.0_05