user3034773 user3034773 - 2 years ago 117
Java Question

Connecting JDBC with SQL Server 2008

I am using following code to get my java application connected with Sql Server 2008.

//connecting java with a different database management system
import java.sql.*;
import java.util.Scanner;

public class MyDatabase {

static Connection conn = null;
static PreparedStatement ps = null;

public static void main(String [] arg) {
String urlp1, urlp2, urlp3;
urlp1 = "jdbc:sqlserver://;";
urlp2 = "servername=HP-PC" + "\\" + "MYINSTANCE;integratedSecurity=true;";
String url = urlp1 + urlp2;
try {
catch (Exception e) {
System.out.println("Exception 1");
try {
conn = DriverManager.getConnection(url, "sa", "admin");
catch (Exception ec) {
System.out.println("Exception 1 Part 2");
try {
System.out.println("Enter name:");
Scanner scan = new Scanner(;
String name = scan.nextLine();
System.out.println("Enter age:");
int age = scan.nextInt();
String query = "insert into table1(Stuname,Age) values(?,?);";
ps = conn.prepareStatement(query);
ps.setString(1, name);
ps.setInt(2, age);
catch (Exception e1) {
System.out.println("Exception 2");
finally {
try {
catch (Exception e2) {
System.out.println("Exception 3");

I have downloaded "sqljdbc4.0.jar" file and using following command in cmd to locate the address of the SQLServerDriver class-:

set classpath=.;D:\Java\jre\bin\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar

The problem is data is not entered in the table. Neither any error nor any exception is being shown.
I've gone through a lot of solutions on the internet but none of them is working.
How can I accomplish this??

Answer Source

I assume you are not getting any connection

 System.out.println("Enter name:");
        Scanner scan=new Scanner(;
        String name=scan.nextLine();
        System.out.println("Enter age:");
        int age=scan.nextInt();
        String query="insert into table1(Stuname,Age) values(?,?);";

       // you have forget to submit your changes to the database. try with following line of code
        ps.execute() or ps.executeQuery()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download