连接MySQL数据库的完整代码⾸先导⼊mysql-connector-java-5.0.8-bin.jar
1、创建配置⽂件jdbc.properties
jdbc.sql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shop
jdbc.username=root
jdbc.password=123456
2、读取配置⽂件类
package com.hx.shopping.util;
import java.io.IOException;
import java.util.Properties;
public class PropUtil {
private static Properties prop = null;
public static Properties getProp(String fileName){
if(prop==null){
prop = new Properties();
try {
//ClassLoader()得到src根路径
prop.load(ClassLoader().getResourceAsStream(fileName));
蔺怎么读} catch (IOException e) {
e.printStackTrace();
}
}
return prop;过生日送什么礼物
}
}
3、连接MySQL类
package com.hx.shopping.util;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
static Properties prop = Prop("jdbc.properties");//只写等号后半部分⽆法识别
/*
* 加载驱动
*/
public static final String driver = Property("jdbc.driver");
/*
* 连接数据库的URL,端⼝号是数据库的端⼝号:3306,⽽不是8080
*/
public static final String url = Property("jdbc.url");
/*
* ⽤户名
* ⽤户名
*/
public static final String username = Property("jdbc.username");
/*
* 密码
*/
public static final String password = Property("jdbc.password");
/*
* 使⽤静态代码块加载驱动
*/
static{
try {
Class.forName(driver);
System.out.println("加载驱动成功!!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("加载驱动失败");
}
}
/*
* 连接数据的⽅法
*/
public static Connection getConn(){
Connection conn = null;
try {
conn = Connection(url, username, password);
System.out.println("数据库连接成功!!");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据库连接失败!!");
}
return conn;
}
/*
* 关闭数据库连接
*/
public static void close(Connection conn,CallableStatement cs,ResultSet rs){ try {
if(rs != null){
rs.close();
}
if(cs != null){
cs.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 增删改的实现
*/
public static int changeData(Object[] params,String sql){
Connection conn = null;
Connection conn = null;
七月半写包称呼大全CallableStatement cs = null;
conn = getConn();
int num = -1;
try {
cs = conn.prepareCall(sql);
厦门鼓浪屿特住宿for(int i=0;i<params.length;i++){ cs.setObject((i+1), params[i]); }
num = cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(cs != null){
cs.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return num;
什么是燃油附加费>qq签名}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论