0% found this document useful (0 votes)
6 views2 pages

JDBC Database Connectivity in Java

The document provides examples of how to connect to a database in Java using JDBC for both MySQL and SQL Server. It includes sample code for establishing a connection, executing a query, and handling exceptions. Users are advised to ensure their databases are created before running the code.

Uploaded by

afsahhaseeb9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

JDBC Database Connectivity in Java

The document provides examples of how to connect to a database in Java using JDBC for both MySQL and SQL Server. It includes sample code for establishing a connection, executing a query, and handling exceptions. Users are advised to ensure their databases are created before running the code.

Uploaded by

afsahhaseeb9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

JDBC Database Connectivity in Java

Topic#1 How to connect Database in Java Using Xampp or MySql.

(Make sure your database is created);

Code:
package javajdbcxampormysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JavaJDBCXampORMYSQL {


public static void main(String[] args) throws SQLException {
try{
String Driver="com.mysql.cj.jdbc.Driver";
String Databaseurl="jdbc:mysql://localhost:3306/testJDBC";
String username="root";
String password="";
Connection conn=DriverManager.getConnection(Databaseurl,username,password);
System.out.println("Database is Successfully Connected");
}
catch(Exception e){
System.out.println(e);
}
}
}

Output:
Topic#1 How to connect Database in Java Using SQL Server.

(Make sure your database is created);

Code:
package javajdbcsql;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;

public class JavaJDBCSQL {


public static void main(String[] args) throws SQLException {
try{
String Driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(Driver);
String Databaseurl="jdbc:sqlserver://DESKTOP-
8THO3D0;databaseName=testJDBC;integratedSecurity=true";
Connection conn=DriverManager.getConnection(Databaseurl);
Statement state = conn.createStatement();
String query="Select * from Person";
ResultSet rs= state.executeQuery(query);
while(rs.next()){

System.out.println(rs.getInt(1)+rs.getString(2)+rs.getString(3)+rs.getString(4)+rs.getString(5));
}
}
catch(Exception e){
System.out.println(e);
}
}
}

Output:

You might also like