package com.szb.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Dbutil2 {
private static String driver;
private static String url;
private static String username;
private static String password;
static {//初始化参数
driver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://localhost:3306/db_jxgl";
username = "root";
password = "123456";
}
public static Connection open() {//建立数据库连接
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void close(Connection conn) {//关闭数据库连接
if (conn!= null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}有了这个类后,对数据库的访问会更加方便,下面代码与昨天的比较,更简洁一些吧。
package com.szb.dbutil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Dbutil1_2 {
public static void main(String[] args) {
Connection conn = Dbutil2.open();//建立数据库连接
String sql = "select id,stu_id,name from student";
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);//执行语句
while (rs.next()) {
int id = rs.getInt(1);
int stu_id = rs.getInt(2);
String name = rs.getString(3);
System.out.println("id:"+id+" ,stu_id:"+stu_id+" ,name:"+name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
Dbutil2.close(conn);//关闭连接
}
}
}
这是执行结果:查出了王五 王六
再分享一个今天遇到的问题:
我想将一个名为db_register的数据库备份出来,保存 .sql文件,用命令 mysqldump -u root -p db_register > f:/db_register.sql 随手打了一个分号 这是好多人的习惯了。。 结果报错了。原来没有进入MySQL时不算是输入SQL命令。所以不用分号。牢记! 请看下图:

857



被折叠的 条评论
为什么被折叠?



