How to setup Connection to Database
Prerequisites:
1. Installed MySQL
2. IDE (I'm using Eclipse)
Steps
Step 1.: Create Database that you want to connect. Here I'm using mydb.
SQL Query:
create database mydb;
use mydb;
show databases;
create table account(accno int,lastname varchar(25),firstname varchar(25),bal int)
select * from account;
Step 2: Creating Java Project in Eclipse
Now open Eclipse
Go to File
Select New
Select JAVA Project
Give Name to your project.
Now right click on your project and create a new folder named "lib".
Step 3.: Download Connection/J
Download Platform Independent ZIP Archive
Extract and copy the jar file into lib folder.
Right click on project
Go to properties.
Under Java Build Path add library i.e. Jar file that is in lib folder.
Step 4.: Now create a class in your project.
Write main method.
Code:
package com.mydbpkg.jdbc.dao;
//DAO is a convention for database related code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class AccountDAO {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/mydb","username","passowrd");
// use according to your user name password of sql server
System.out.println(connection);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Post a Comment