在Java语言中如何实现数据库的访问?

如题所述

1.JDBC呗,import java.sql.*;
传统连接方式
Connection conn = getConnection();//获得连接
//注意下边应该抛出个SQLException异常
Statement stat = conn.createStatement();

stat.executeXXX(".........")//执行SQL语句,查询就是Query,插入,修改这种操作就Update

ResultSet result; //查询后返回的结果集用这个保存

conn.close//最后别忘了关闭连接

2.当然是Hibernate了,是一种持久层技术,建立相应的实体后可以把数据库当对象操作,非常方便,具体使用我觉得应该看看书会比较好!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-08-17
给你个连接数据库的DB封装类
import java.sql.*;

public class DB {
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/这里写你的数据库名?user=root&password=这里是你设置的数据库密码");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}

return conn;
}

public static PreparedStatement prepare(Connection conn, String sql) {
PreparedStatement pstmt = null;
try {
if(conn != null) {
pstmt = conn.prepareStatement(sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}

public static PreparedStatement prepare(Connection conn, String sql, int autoGenereatedKeys) {
PreparedStatement pstmt = null;
try {
if(conn != null) {
pstmt = conn.prepareStatement(sql, autoGenereatedKeys);
}
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}

public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
if(conn != null) {
stmt = conn.createStatement();
}
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}

public static ResultSet getResultSet(Statement stmt, String sql) {
ResultSet rs = null;
try {
if(stmt != null) {
rs = stmt.executeQuery(sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

public static void executeUpdate(Statement stmt, String sql) {
try {
if(stmt != null) {
stmt.executeUpdate(sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void close(Connection conn) {
try {
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void close(Statement stmt) {
try {
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void close(ResultSet rs) {
try {
if(rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
下面几句话是连接数据库,并处理的语句:
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DB.getConn();
/**
这里写处理数据库的语句
例如插入删除等
*/
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(pstmt);
DB.close(conn);
}
第2个回答  2011-08-17
可以通过jdbc连接数据库
相似回答