How to connect Java with MySQL/MicrosoftSQL server with pictures


Server Connection with Java using JDBC

In this tutorial I'll tech you how you can connect any database (especially MS SQL Server) with your Java code. I'm using NetBeans (click here to download latest version of NetBeans) IDE to connect MSSQL Database. This is very simple and easy way, just follow the blow steps for connection.

Open MS SQL Server and enter your user name, password and click next as shown in blow fig.


After login into your server. Right click on Databases and select new database as shown blow



A new window will open. Give any name to your database (i.e cs2it.blogspot.com) and click on OK button to execute. Now your database is showing under Databases tag as shown blow.


After creating this database your mission will be to create its connection with you Java Code. So open your IDE (i.e NetBeans) and create new project as shown blow.


A new window will open select Java Application. Give name to your project and click on finish button.  After this add JDBC (Java Database Connectivity) Jar file (Click here to download sqljdbc.jar file) to your project for connectivity with your database. For this right click on libraries and select Add Jar/Folder from menu as shown blow.

A new window will open. Select JDBC (Java Database Connectivity Jar File) path from your computer and click on open button. Jar file will added to your library folder as shown blow.



After adding sqlJdbc jar file, open your main class and paste the blow code under main method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try{
            final String DATABASE_URL = 
            "jdbc:sqlserver://localhost:1433;databaseNam=cs2it.blogspot.com";
            Connection connection = 
            DriverManager.getConnection(DATABASE_URL, "userName", "Password);
            JOptionPane.showMessageDialog(null, "Connection to database is Successful");
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
           
        }

Line no. 2-3 has Database URL for connection. Replace your database name with cs2it.blogspot.com. Line no. 5 has Database URL, Username, Password. Give your MySQL/MS SQL Server userName and Password for connection. The default user name of MSSQL Server is "sa" and password is "123". Line no. 6 displaying that connection is successful.

Your are done with connection. Now click on the run button and you will see connection build successful as shown blow.


Click on the download button for full source code.





Note: Please like, share and comment :D


Comments