您的位置:首页 > 编程语言 > Java开发

Java使用JDBC编写解耦链接数据库

2018-02-01 19:43 507 查看
作者使用的JDBC编写的通用数据库连接代码,通过修改配置文件达到通过一次编写代码实现链接各种数据库,

废话不多说,直接上代码:

<注:配置文件直接在默认包下创建File文件,文件名字命名为jjdbc.properties,就可以了>

代码还是挺简单的,Java基础打得扎实就能看懂。

在编写的时候一定要记得导入 Mysql厂商封装的Jar包

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.Statement;

public class mysqlcont {
public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
Test test = new Test();
String sql = "INSERT INTO Info (name,age,phone) VALUES ('can',22,'2222222')";
Connection connection = test.getConnection();
Statement statement = (Statement) connection.createStatement();
statement.execute(sql);
System.out.println(connection);

}

/*
public static void getConnector() throws SQLException {
Driver driver = new Driver();
String url = "jdbc:mysql://192.168.0.137:3306/Student";
String sql = "INSERT INTO Info (name,age,phone) VALUES ('sang',20,'11111')";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "123456");
Connection connection = (Connection) driver.connect(url, info);
Statement statement = (Statement) connection.createStatement();
statement.execute(sql);
System.out.println(connection);
}*/
}

class Test{
public Connection getConnection() throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
String DriverClass = null;
String jdbcUrl = null;
String user = null;
String pwd = null;

//读取配置文件
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
DriverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
pwd = properties.getProperty("password");
Driver driver = (Driver) Class.forName(DriverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password",pwd);
Connection connection = (Connection) driver.connect(jdbcUrl, info);
return connection;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: