关闭

Java操作数据库

标签: java数据库
65人阅读 评论(0) 收藏 举报

简单建立连接并查询

import java.sql.*;

public class dbtest
{
    public static void main(String[] args) 
    {
        dbtest ora = new dbtest();
    }

    public dbtest()
    {
        Connection con = null;
        PreparedStatement pre = null;
        ResultSet res = null;
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            System.out.println("开始尝试连接数据库!");
            String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
            String user = "cashier_01";
            String password = "cashier";
            con = DriverManager.getConnection(url, user, password);
            System.out.println("连接成功!");
        }catch (Exception e){
            System.out.println("连接失败!");
            System.out.println(e);
        }
        if (con != null){
            try{
                System.out.println("SQL结果如下:");
                String sql = "select * from manager_01.mem_card where cname = ?";       
                pre = con.prepareStatement(sql);
                pre.setString(1, "小蔡");
                res = pre.executeQuery();
                while (res.next())
                    System.out.println("卡号:" + res.getInt("cno")
                        + "\t姓名:" + res.getString("cname") 
                        + "\t积分:" + res.getString("point"));
            }catch(Exception e){
                System.out.println("SQL语句有误!");
                System.out.println(e);
            }
        }
        else
            System.out.println("连接未建立!");
        try {
            if (res != null)    res.close();
            if (pre != null)    pre.close();
            if (con != null)    con.close();
            System.out.println("数据库连接已关闭!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

获取当前时间并插入数据库

int cardNumber = 10;
String sqlstr = null;
PreparedStatement pre = null;       
Timestamp createDate = new Timestamp((new java.util.Date()).getTime());
try {
    sqlstr = "insert into manager_01.mem_card(cno, cname, cdate, point) values(?, ?, ?, 0)";
    pre = db.con.prepareStatement(sqlstr);
    pre.setInt(1, cardNumber);
    pre.setString(2, "路人甲");
    pre.setTimestamp(3, createDate);
    pre.execute();
} catch (Exception e) {
    System.out.println(e);
    e.printStackTrace();
} finally {
    try {
        if (pre != null)
            pre.close();
    } catch (Exception e2) {
        System.out.println(e2);
        e2.printStackTrace();
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1200次
    • 积分:142
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类