mysql jdbc的使用
2016-02-06 18:45
465 查看
先创建一个库petdb, 再创建一个表pettable,在里面加入数据。
使用jdbc读出。
使用jdbc读出。
import java.sql.*; /** * Created by chuiyuan on 2/6/16. */ public class mysql { /** * JDBC driver name and database URL */ static final String DB_NAME="petdb"; static final String TABLE_NAME="pettable"; static final String JDBC_DRIVER ="com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/"+DB_NAME; /** * database credentials */ static final String USER = "petuser"; static final String PASSWD = "petpwd"; public static void main(String [] args){ Connection conn = null ; Statement stmt = null; try { /** * register jdbc driver */ Class.forName(JDBC_DRIVER); /** * open a connection */ System.out.println("Connect to databse ...."); conn = DriverManager.getConnection(DB_URL, USER, PASSWD); /** * execute a query */ System.out.println("creating statement"); stmt = conn.createStatement() ; String sql; sql = "select * from "+ TABLE_NAME; ResultSet rs = stmt.executeQuery(sql); /** * extract data from result set */ while (rs.next()){ //retrive by last column name String name = rs.getString("name"); String species = rs.getString("species"); //Date birth = rs.getDate("birth"); Date death = rs.getDate("death") ; //display System.out.print("name:"+ name); System.out.print(", species:"+ species); //System.out.print(", birth:"+birth); System.out.println(", death:"+ death); } /** * clean up environment */ rs.close(); stmt.close(); conn.close(); }catch (Exception e){ e.printStackTrace(); }finally { /** * used to close resources */ try { if (stmt!=null){ stmt.close(); } }catch (SQLException se){ se.printStackTrace(); } try { if (conn!=null){ conn.close(); } }catch (SQLException se1){ se1.printStackTrace(); } } } }
相关文章推荐
- 完全卸载mysql数据库图文教程
- MySQL 採用Xtrabackup对数据库进行全库备份
- mysql服务老是不见
- Ubuntu14.04下安装MySQL
- mysql-server/mysql-client区别
- mysql免安装版的配置
- Mysql常识
- mysql水平分表
- MySQL Workbench 修改快捷键
- High Performance MySQL Chapter2
- mysql批量插入数据脚本
- VS2013使用EF6与mysql数据库
- 《MySQL必知必会》读书笔记(二) 8~14章
- mysql的密码重置
- mysql_real_escape_string总是返回false
- MySQL 视图之创建、查看、修改
- MySQL日志
- MySQL存储引擎介绍
- MySQL多实例管理
- MySQL之grant、revoke用法