比这篇新的文章: Codee#1327
比这篇旧的文章: maximum command line parameter length? 命令行参数可以有多长?

Codee#1326 编辑代码

语言: Java, 标签: 无  2009/05/20发布 10个月前更新 | 编辑代码
作者: , 点击179次, 评论(0), 收藏者(0), , 打分:

背景
主题: 字体:
Java语言: Codee#1326
01 import java.sql.SQLException;
02
03 public class JDBCHelloWorld {
04     public static void main(String[] args) {
05         // 1. 注册驱动
06         try {
07             Class.forName("com.mysql.jdbc.Driver");
08         } catch (ClassNotFoundException e) {
09             // TODO Auto-generated catch block
10             e.printStackTrace();
11         }// Mysql 的驱动
12         // 先定义变量,后使用和关闭
13         java.sql.Connection conn = null;// 数据库连接
14         java.sql.Statement stmt = null;// 数据库表达式
15         java.sql.ResultSet rs = null;// 结果集
16         try {
17             // 2. 获取数据库的连接
18             conn = java.sql.DriverManager
19                     .getConnection(
20                             "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8",
21                             "root", "sld"); // 用户名,密码
22             // 3. 获取表达式
23             stmt = conn.createStatement();
24             // 执行创建表的SQL
25             stmt
26                     .executeUpdate("CREATE TABLE Student(        id int NOT NULL auto_increment,                    username varchar(200) NOT NULL,                password varchar(20) NOT NULL,                age int,                PRIMARY KEY (id)                ) ENGINE=MyISAM DEFAULT CHARSET=UTF8                ");
27             // 执行插入数据的 SQL
28             stmt
29                     .executeUpdate("insert into Student(username, password,age) values('张三', '1234', 20)");
30             // 4. 执行 SQL
31             rs = stmt.executeQuery("select * from Student");
32             // 5. 显示结果集里面的数据
33             while (rs.next()) {
34                 System.out.println("编号=" + rs.getInt(1));
35                 System.out.println("学生姓名=" + rs.getString("username"));
36                 System.out.println("密码=" + rs.getString("password"));
37                 System.out.println("年龄=" + rs.getString("age"));
38             }
39             // 执行删除数据的 SQL
40             // stmt.executeUpdate("delete from Student");
41         } catch (SQLException e) {
42             e.printStackTrace();
43         } finally {
44             // 6. 释放资源,建议放在finally语句中确保都被关闭掉了
45             try {
46                 rs.close();
47             } catch (SQLException e) {
48             }
49             try {
50                 stmt.close();
51             } catch (SQLException e) {
52             }
53             try {
54                 conn.close();
55             } catch (SQLException e) {
56             }
57         }
58     }
59 }


所有评论,共0条:( 我也来说两句)


发表评论

注册登录后再发表评论