Today I'm going to show you how to connect to a Mysql database using Java code and execute some SQL queries. To do this coding parts I'm going to use the Java project we had created in the last lesson and the database we have to create in the 3rd lesson Create Mysql Database.
To connect the Mysql database to Java code we have to follow the following 4 steps.
1.Load Mysql JDBC Driver
2.Create a Connection to "MySQL"
3.Create a Statement
4.execute "SQL string"
2.Create a Connection to "MySQL"
3.Create a Statement
4.execute "SQL string"
Let's do the coding,
Here you can see the basic parts of the code but there are some errors in this code let's fix them.
1. import java.sql.*;
2. throws ClassNotFoundException
3. throws SQLException
Just for a few upcoming posts, we import all classes and sub packagers in java.sql. Here we can catch or throws the above exception. Both of those options can fix the problem but it is not a good programming practice to catch exception here we must throw them to user interface and in the user interface we have to catch them.
Following is the corrected code
Let's run this code and insert data to the user table.
When you try to run this code you will get the following error.
This happens because we didn't add JDBC driver to the project yet let's add that,
Right-click on libraries
Then select add libraries,
Select Mysql JDBC Driver
Add the library. Run the code,
Let's take a look at the database,
We have successfully inserted the data to the table via Java code. Catch you guys in my next post bye..!








No comments:
Post a Comment