JDBC链接&关闭

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.shop.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBC {
private static String url = null;
private static String name = null;
private static String password = null;

static {
try {
Class.forName ( "com.mysql.cj.jdbc.Driver" );
} catch (Exception e) {
e.printStackTrace ( );
}
url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8&useSSL=true";
name = "root";
password = "csh20011103";
}

public static Connection getConn() throws Exception {
return DriverManager.getConnection ( url, name, password );
}

public static void release(Connection conn, PreparedStatement pst, ResultSet res) {
try {
if (res != null) {
res.close ( );
}
if (pst != null) {
pst.close ( );
}
if (conn != null) {
conn.close ( );
}
} catch (Exception e) {
e.printStackTrace ( );
}
}
}

登录

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
31
32
33
public class User {
Connection conn = null;
PreparedStatement pst = null;
ResultSet res = null;
boolean isQ;

public boolean Select(String username, String paw) {
try {
conn = JDBC.getConn();
String sql = "SELECT * FROM user where `Username`=? and `Password`=?;";
pst = conn.prepareStatement(sql);
pst.setObject(1, username);
pst.setObject(2, paw);
System.out.println(sql);
res = pst.executeQuery();
if (res.next()) {
isQ = true;
System.out.println(res.getObject("name") + " " + res.getObject("password"));
System.out.println("登陆成功");
} else {
isQ = false;
System.out.println("登陆失败");
}
} catch (Exception e) {
System.out.println("NO!");
e.printStackTrace();
} finally {
JDBC.release(conn, pst, res);
}
return isQ;
}
}