Java 建立mysql数据库连接的语句

时间:2023-03-09 19:15:18
Java 建立mysql数据库连接的语句
每次在面试时被问到jdbc的数据路链接过程都卡着,这次不怕了,背会了。。。
第一个,比较粗糙的

try{
 

Class.forName("com.mysql.jdbc.Driver");

}

catch(ClassNotFoundException e) {}

//定义所要用到的三个数据库应用对象

Connection con=null; //连接对象

Statement sql=null; //Statement对象(SQL语句)

ResultSet rs=null; //结果集对象

//进行数据源的连接

try{
 

con=DriverManager.getConnection ("jdbc:mysql://localhost/scutcs","","");//连接数据库的url 用户名和密码

sql=con.createStatement();

String to="Select * From user1 Where username='"+username+"'";

rs=sql.executeQuery(to); //根据所定义的Statement执行生成相应的结果集并存在RS中

if(rs.next()) //判断结果集是否为空,如果不为空则表示有记录

{

out.print("<script>alert('用户名 "+xm+"已存在,请另选一个!');history.back();</script>");//如果存在返回注册页面

}

else {如果不存在就向数据库添加一条记录}

}

catch (SQLException e)
 

{ out.print(e);
 

}

第二个 ,作为公共类比较完整些的  把部分的定义为单个函数方便调用
import java.sql.*;

public class DB {

public static Connection getConn() {

Connection conn = null;

try {

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=root&password=123456");

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

public static PreparedStatement prepare(Connection conn, String sql) {

PreparedStatement pstmt = null;
 

try {

if(conn != null) {

pstmt = conn.prepareStatement(sql);

}

} catch (SQLException e) {

e.printStackTrace();

}

return pstmt;

}

public static PreparedStatement prepare(Connection conn, String sql, int autoGenereatedKeys) {

PreparedStatement pstmt = null;
 

try {

if(conn != null) {

pstmt = conn.prepareStatement(sql, autoGenereatedKeys);

}

} catch (SQLException e) {

e.printStackTrace();

}

return pstmt;

}

public static Statement getStatement(Connection conn) {

Statement stmt = null;
 

try {

if(conn != null) {

stmt = conn.createStatement();

}

} catch (SQLException e) {

e.printStackTrace();

}

return stmt;

}

/*

public static ResultSet getResultSet(Connection conn, String sql) {

Statement stmt = getStatement(conn);

ResultSet rs = getResultSet(stmt, sql);

close(stmt);

return rs;

}

*/

public static ResultSet getResultSet(Statement stmt, String sql) {

ResultSet rs = null;

try {

if(stmt != null) {

rs = stmt.executeQuery(sql);

}

} catch (SQLException e) {

e.printStackTrace();

}

return rs;

}

public static void executeUpdate(Statement stmt, String sql) {

try {

if(stmt != null) {

stmt.executeUpdate(sql);

}

} catch (SQLException e) {

e.printStackTrace();

}

}

public static void close(Connection conn) {

try {

if(conn != null) {

conn.close();

conn = null;

}

} catch (SQLException e) {

e.printStackTrace();

}

}

public static void close(Statement stmt) {

try {

if(stmt != null) {

stmt.close();

stmt = null;

}

} catch (SQLException e) {

e.printStackTrace();

}


}