Java操作数据库

简单建立连接并查询

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值