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();
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zwj5361826/article/details/51550252
文章标签: java 数据库
上一篇数据库入门
下一篇Java 相关
想对作者说点什么? 我来说一句

JAVA操作数据库三层

2009年07月01日 2.18MB 下载

关系型数据库的并发操作

2010年02月02日 307KB 下载

没有更多推荐了,返回首页

关闭
关闭