Lab 2
Lab 2
Enter the following command and select Execute (Or press F5)
CREATE DATABASE EMPDB
Create Table:
Note, in a window editor, if we write many commands, which statement we want to execute, we must
select that statement.
Download JDBC Driver and add sqljdbc42.jar to Java project using NetBeans by following steps
Specify the folder containing the JDBC Driver and select the file sqljdbc42.jar -> select Open
SQL Server JDBC connection string:
Each database management system will have a different connection string. Following is the JDBC
connection string for Microsoft SQL Server
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
serverName is the server name or IP address of the machine where Microsoft SQL Server is installed
instanceName is the name of an instance to connect to serverName. If this parameter is not specified,
the default instance will be used
establish connection:
String dbURL =
"jdbc:sqlserver://localhost;databaseName=EMPDB;user=sa;password=123";
Connection conn = DriverManager.getConnection(dbURL);
if (conn != null) {
System.out.println("Connected");
}
In order for the above code to execute successfully, we have to do 2 things
The first thing: Set up SQL Server to allow login using SQL Server's account
Set password
Activate the sa account: select Enable in the Login section (this account is disabled by default)
Example program:
package jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConnectionTest {
public static void main(String[] args) {
try {
String dbURL =
"jdbc:sqlserver://localhost;databaseName=EMPDB;user=sa;passwo
rd=123";
Connection conn = DriverManager.getConnection(dbURL);
if (conn != null) {
System.out.println("Connected");
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " +
dm.getDatabaseProductName());
System.out.println("Product version: " +
dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
System.err.println("Cannot connect database, " + ex);
}
}
}
You write a program that executes the following requirements: