jdbc连接数据库
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
jdbc连接数据库步骤:
1选择数据库类型和导入JAR包;2加载驱动(Class.forName("com.mysql.jdbc.Driver"));3获取数据库连接(DriverManager.getConnection(url, user, password););
4创建Statement对象;5调用statement执行相应的SQL;6关闭数据库连接。
-----------------------------------------------------------------------bd连接-------------------------------------------------------------------------------------
public class Dbhelper {
String url="jdbc:mysql://localhost:3306/test";
String password="pwd123qwer";
String user ="root";
private static Connection con=null;
public ResultSet rs = null;
public PreparedStatement pst = null;
public Dbhelper(String sql){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close(){
try {
this.con.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------测试连接--------------------------------------------------------------------------------------------------------
public class TestDB {
static String sql=null;
static Dbhelper db = null;
static ResultSet rs = null;
public static void main(String[] args) {
sql="select * from customer";
db = new Dbhelper(sql);
try {
rs = db.pst.executeQuery();
JSONObject object = new JSONObject();
object.put("rs", rs);
System.out.println(object.get(rs).toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
}