about how to write a database connection for a Java Web project

Source: Internet
Author: User

Although the study javaweb time is not long, also did some small projects. However, I still often forget about connecting to the database code, always need to go over the notes. Today you want to save some notes, if necessary later, you can find here.

Code:

Import java.sql.Connection;

Import Java.sql.DriverManager;

Import java.sql.PreparedStatement;

Import Java.sql.ResultSet;

Import java.sql.SQLException;



public class Jdbctools {

private static String driver= "Com.mysql.jdbc.Driver";

Oracle is: "Oracle.jdbc.driver.OracleDriver"

SQL Server is: "Com.microsoft.sqlserver.jdbc.SQLServerDriver"

private static String url= "Jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf8";

Oracle: "Jdbc:oracle:thin: @localhost: 1521:orcl"

SQL Server is: "jdbc:sqlserver://localhost:1433;database= database Name"


private static String username= "root";

private static String password= "sleeping";

public static Connection getconnection () {

Connection Conn=null;

try {

Class.forName (driver);

Conn=drivermanager.getconnection (Url,username,password);

System.out.println ("connected successfully");

catch (Exception e) {

System.out.println ("Connection failed");

TODO auto-generated Catch block

E.printstacktrace ();

}

Return conn;

}

public static void Release (ResultSet rs,preparedstatement pstmt,connection conn) {

try {

if (rs!=null)

{Rs.close ();} else if (pstmt!=null)

{Pstmt.close ();} else if (conn!=null)

{Conn.close ();}

catch (Exception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.