JDBC连接mysql需要安装先安装mysql-connector-java.
本例实现,连接mysql,从test数据库emp(name,age)表中查询信息并输出到Console
- import java.sql.*;
- public class TestJDBC {
- public static void main(String[] args){
- ResultSet rs = null;
- Statement stmt = null;
- Connection conn = null;
- //http://dev.mysql.com/downloads/connector/j/3.0.html
- //将mysql-connector-java-5.0.8-bin.jar加入classpath,放入WEB-INF/lib
- //
- try{
- Class.forName("com.mysql.jdbc.Driver");
- String URL = "jdbc:mysql://localhost:3306/test";
- String user = "root";
- String password = "root";
- //连接数据库
- conn = DriverManager.getConnection(URL, user, password);
-
- stmt = conn.createStatement();
- String Sql = "Select * from emp";
- rs = stmt.executeQuery(Sql);//执行sql查询
- while(rs.next()){
- System.out.print(rs.getString("name")+" -");
- System.out.print(rs.getString("age")+"\n");
- }
- }catch(ClassNotFoundException e){
- e.printStackTrace();
- }catch(SQLException e){
- e.printStackTrace();
- }finally{
- try{
- if(rs != null){
- rs.close();
- rs = null;
- }
- if(stmt != null){
- stmt.close();
- stmt = null;
- }
- if(conn != null){
- conn.close();
- conn = null;
- }
- }catch(SQLException e){
- e.printStackTrace();
- }
- }//end finally
- }//end main
-
-
- }
- /*
- -----------------------------------------------------
- C:\myeclipseApp\hiworld\src>javac TestJDBC.java
- C:\myeclipseApp\hiworld\src>java TestJDBC
- Henry -11
- Ella -12
- */
- mysql> use test;
- Database changed
- mysql> create table emp(
- -> name char(20),
- -> age int);
- Query OK, 0 rows affected (0.10 sec)
- mysql> insert into emp values('Henry',11);
- Query OK, 1 row affected (0.06 sec)
- mysql> insert into emp values('Ella',12);
- Query OK, 1 row affected (0.05 sec)
- mysql> select * from emp;
- +-------+------+
- | name | age |
- +-------+------+
- | Henry | 11 |
- | Ella | 12 |
- +-------+------+
- 2 rows in set (0.00 sec)
- -----------------------------------------------------
- C:\myeclipseApp\hiworld\src>javac TestJDBC.java
- C:\myeclipseApp\hiworld\src>java TestJDBC
- Henry -11
- Ella -12
阅读(862) | 评论(1) | 转发(0) |