How to Connect to MySQL from Java

7,143
-1

Published on

This tutorial tells you how to connect to MySQL from Java. This tutorial assumes you are using XAMPP and NetBeans.

If you are using different text editors or not using XAMPP, the steps might be a little bit different.

Published in: Technology
1 Comment
2 Likes
Statistics
Notes
  • I M NOT ABLE COMPILE THE CODE?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
7,143
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
314
Comments
1
Likes
2
Embeds 0
No embeds

No notes for slide

How to Connect to MySQL from Java

  1. 1. HOW  TO  CONNECT  TO  MYSQL  USING  JAVA   1  How to Connect to MySQL using JavaAssuming You’re using XAMPP and NetBeansPrerequisites: 1. Installed XAMPP 2. NetBeans + JDKIf you don’t use XAMPP and NetBeans, the steps might be different. You might have to find asolution on your own.Getting Ready1. Create a new Java Application project. You can give any name you wish.2. Right click on Libraries node and click Add Library…3. Find MySQL JDBC Driver and click Add Library. Copyright © 2011 Fiona Angelina W
  2. 2. HOW  TO  CONNECT  TO  MYSQL  USING  JAVA   2  4. Open your XAMPP Control Panel and ensure the Apache and MySQL server is running.5. Open your favorite browser and type: http://localhost/phpmyadmin/. Create a database withany name. In this case, I create a database named mydatabase. Click Create.A successful message will appear.5. Now go back to your main class and copy paste the following code (when presented bymore than 1 import, choose the one that starts with java.sql.xxx). Change the dbName toyour database name. Don’t forget to change the username and password as well. In thiscase, my MySQL username is root and the password is blank. Change the host if you installMySQL using different hostname. Don’t forget to close the connection! String  host  =  "jdbc:mysql://localhost:3306/";                     String  dbName  =  "scheherazade";                     String  username  =  "root";                     String  password  =  "";                                       String  url  =  host  +  dbName  +  "?user="  +  username  +  "&password="  +  password;                                       try{                       Class.forName("com.mysql.jdbc.Driver");                             Connection  conn  =  DriverManager.getConnection(url);                               /*                             You  can  execute  SQL  statement/query  here                             */   conn.close();   System.out.println("Succeed!");                     }                     catch(ClassNotFoundException  e){   System.out.println("Class  not  found!");                     }                     catch(SQLException  e){                             System.out.println("SQL  exception!");                     }   Copyright © 2011 Fiona Angelina W
  3. 3. HOW  TO  CONNECT  TO  MYSQL  USING  JAVA   3  6. Try compile and running. If connection is successful, a message “Succeed!” will appear inthe command prompt.Executing a StatementThere are three types of executing a statement: 1. execute() can be used to execute any kind of statements. 2. executeQuery() will return ResultSet. executeQuery() is used to execute statement that produces result. 3. executeUpdate(), I rarely use this. Therefore I don’t really have a clue. This is the description I copy pasted from the JavaDocs: “Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement”.Try copy paste the code below (erase the comment part): Statement  stat  =  conn.createStatement();   stat.execute("CREATE  TABLE  student(id  int,  name  varchar(50),  batch  varchar(4))");    Compile and run the program. A new student table will be created with the followingcolumns: id, name, and batch.Remove the previous code, and try to populate the student database. Statement  stat  =  conn.createStatement();   stat.execute("INSERT  INTO  student  VALUES(1,  dono,  2013)");   stat.execute("INSERT  INTO  student  VALUES(2,  kasino,  2014)");   stat.execute("INSERT  INTO  student  VALUES(3,  indro,  2012)");  Check the content of your table.Getting a ResultSet from a StatementRemove the previous code and try to execute a query. To execute a query, we have to callthe executeQuery() method. Statement  stat  =  conn.createStatement();   ResultSet  result  =  stat.executeQuery("SELECT  *  FROM  student");   Copyright © 2011 Fiona Angelina W
  4. 4. HOW  TO  CONNECT  TO  MYSQL  USING  JAVA   4  To iterate the result, use the code below: while(result.next()){   System.out.println(result.getInt(1)  +  ",  "  +  result.getString(2)  +  ",  "  +   result.getString(3));   }  Explanation: • getInt() method is used if the column has an int data type. In this case, id is int, therefore we use getInt() method. • getString() method is used if the column has a varchar data type. In this case, name and batch are varchar, therefore we use getString() method. • There are more get methods for specific data types such as: o getDouble() for double o getBoolean() for bool o etc. • Inside each get method, we insert the column number: o 1 refers to the first column which is id o 2 refers to the second column which is name o 3 refers to the third column which is batchNotes:There are many ways to execute MySQL statement. For example: • Using PreparedStatement • Using executeUpdate() • Inserting the column name instead of the column number • Etc.Try to research on your own J Good luck. Copyright © 2011 Fiona Angelina W

×