Java jdbc测试mysql数据库代码。
工具 eclipse,jdk1.8,mysql
注意:要配置mysql.jar
import java.sql.SQLException;
/**
* @author lengol
*
*/
public class TestMysql {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
//1.注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2.创建数据库的连接
//useUnicode=true&characterEncoding=GBK:支持中文
java.sql.Connection conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost/lesson?useUnicode=true&characterEncoding=utf8",
"root", " ");
//3获取表达式SQL
java.sql.Statement stmt = conn.createStatement();
//4.执行SQL
String sql = "select * from study";
java.sql.ResultSet res = stmt.executeQuery(sql);
//5.打印结果集里的数据
while(res.next()) {
System.out.print("the id: ");
System.out.println(res.getInt(1));
System.out.print("the username: ");
System.out.println(res.getString("username"));
System.out.print("the class: ");
System.out.println(res.getString("sex"));
System.out.println();
}
//测试插入数据库的功能:
//String inSql = "insert into test(user,addr) values('插入2','新地址2')";
//stmt.executeUpdate(inSql);
//6.释放资源,关闭连接(这是一个良好的习惯)
res.close();
stmt.close();
conn.close();
}
}