Java is a popular language or may be the most popular language now. From this post I'm going to show how to connect MySQL database to java program. (this is a simple program with simple db)
1. You need to create a data base in MySQL and create a table. Then you can insert values to the table. If you are not familiar then use following lines. ( red color : not syntax )
mysql> CREATE DATABASE myData;
mysql> GRANT ALL ON myData.* TO name@localhost IDENTIFIED BY 'password';
mysql> use myData
mysql> create table student(name varchar(30), city varchar(30));
mysql> insert into student values("Amy","Texas");
2. Now you need to download MySQL java connector. click for Windows download ZIP Archive and for Linux download TAR Archive
3. Extract the downloaded file and check the mysql-connector-java-5.1.16-bin.jar file is available or not. If not then you need to check again.....
5. In the project window right click on the Libraries (which placed under your created project name) and select Add Jar/Folder.
6. After adding the Jar file it will display like this.
7. Now the rest of the coding is simple.
line 1 : you need to import java.sql package.
line 8 : defining Driver class. You can find these things in project window. (you need to expand the .jar file)
line 10 - 12 : passing parameters to open the connection. angmar is the user name which I have created earlier and angmar123 is the password. myData is the DB and localhost:3306 is explained at the end of this post.
line 14 : This line is to prepare a statement (a Query) and it creates in statement object.
line 16 : To execute the prepared query this line can be use. The result is stored as result object which has been create by using ResultSet class.
line 18 : Return a boolean type value (true or false)
line 20 : To get the the result as a String .getString() method can be use. 1 will gives the 1st value.
- localhost:3306 -> MySQL is using port 3306. To get that you can run following commands in CMD or Terminal.
Windows:
:> netstat -ano
you will get the pid, use task manager to get the correct application or service to that pid.
Linux:
# nmap -sS localhost
you need to install nmap to execute this command.