Home > Java > Database Connections in Java

Database Connections in Java

Before giving structures, we need to notice a little detail about making database connections in Java. All database connections must be stated in try and catch statements, because there is a possibility of getting an exception. That’s way, we try to make our connection in try statement. If our connection attempt fails, that means there is an exception, and the exceptions must be catched.

1.1) MS SQL Connection in Java

Example 1.1: MakingConnections.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.sql.*;

public class MakingConnections {
   static Connection myconn = createSQLConnection();

   public static Connection createSQLConnection(){

      try {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         }
      catch(java.lang.ClassNotFoundException e) {
         System.err.print("Class Not Found Exception: ");
         System.err.println(e.getMessage());
      }

      try {
         myconn = DriverManager.getConnection("jdbc:odbc:Driver={SQL Server};server=127.0.0.1;uid=javalogin;pwd=123456;database=javadb");
      }
      catch(SQLException ex) {
         System.err.println("SQL Exception: " + ex.getMessage());
      }

      return myconn;
   }
         
   public static void main(String[] args) {
      // TODO Auto-generated method stub
   }

}

You can determine the server, uid, pwd and database variables as you need.

As you see, we wrote our createSQLConnection() function to create our database connection. You can use this function to create a Statement to manage your records like this:

Example 1.2: An addition to Example 1.1

1
2
3
4
5
6
7
try{
Statement ourStatement = mycon.createStatement();
}

catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}


If you don’t know how to create and use statements in Java, you have to wait a little bit for our next articles that will contain detailed information and clues about how to use statements and manage database records in Java.

Bookmark and Share
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker