1、数据库配置文件(mysql5.xx和8.xx的编写有差异)
driver=com.mysql.jdbc.Driver
url=jdbc: mysql: //127.0.0.1: 3306/smbms? useSSL=false&useUnicode =true&characterEncoding =utf- 8
user=root
password=root
2、JDBC基础公共类
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
Properties properties = new Properties ( ) ;
InputStream is = BaseDao. class . getClassLoader ( ) . getResourceAsStream ( "db.properties" ) ;
try {
properties. load ( is) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
driver = properties. getProperty ( "driver" ) ;
url = properties. getProperty ( "url" ) ;
username = properties. getProperty ( "username" ) ;
password = properties. getProperty ( "password" ) ;
}
public static Connection getConnection ( ) throws ClassNotFoundException, SQLException {
Connection connection = null;
Class. forName ( driver) ;
connection = DriverManager. getConnection ( url, username, password) ;
return connection;
}
public static ResultSet execute ( Connection connection, String sql, Object[ ] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection. prepareStatement ( sql) ;
for ( int i = 0 ; i < params. length; i++ ) {
preparedStatement. setObject ( i + 1 , params[ i] ) ;
}
resultSet = preparedStatement. executeQuery ( sql) ;
return resultSet;
}
public static int update ( Connection connection, String sql, Object[ ] params, PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection. prepareStatement ( sql) ;
for ( int i = 0 ; i < params. length; i++ ) {
preparedStatement. setObject ( i + 1 , params[ i] ) ;
}
int updateRows = preparedStatement. executeUpdate ( ) ;
return updateRows;
}
public static boolean closeResource ( Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
boolean flag = true ;
if ( resultSet != null) {
try {
resultSet. close ( ) ;
resultSet = null;
} catch ( SQLException throwables) {
throwables. printStackTrace ( ) ;
flag = false ;
}
}
if ( preparedStatement != null) {
try {
preparedStatement. close ( ) ;
resultSet = null;
} catch ( SQLException throwables) {
throwables. printStackTrace ( ) ;
flag = false ;
}
}
if ( connection != null) {
try {
connection. close ( ) ;
resultSet = null;
} catch ( SQLException throwables) {
throwables. printStackTrace ( ) ;
flag = false ;
}
}
return flag;
}
}