当前位置: 代码迷 >> J2EE >> 用Java连接数据库和简单的数据库操作代码,该如何处理
  详细解决方案

用Java连接数据库和简单的数据库操作代码,该如何处理

热度:118   发布时间:2016-04-22 02:54:28.0
用Java连接数据库和简单的数据库操作代码

那位能不能给一个Java(NetBean和eclipse)操作数据库的代码实例,只要包括最一个表insert数据、更新数据、删除数据和查询数据就可以,谢谢!

------解决方案--------------------
package com.kp.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * 连接数据库
 * @author Administrator
 *
 */
public class ConnDB {
public static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=UsersDB";
public static Connection getConn(){
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL,"sa","123");
} catch (Exception e) {
// TODO: handle exception
}
return conn;
}
//关闭链接
public static void close(ResultSet rs,Statement st,Connection conn){
try {
if(rs != null){
rs.close();
}
if(st != null){
st.close();
}
if(conn != null){
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

//User这个实体类必须得有哦

//增加一个用户
public int insert(User user){
int result = 0;
Connection conn = null;
PreparedStatement pt = null;
String sql = "insert UserInfo values(?,?,?,?,?,?,?,?)";
try {
conn =ConnDB.getConn();
pt = conn.prepareStatement(sql);
pt.setString(1, user.getUserName());
pt.setString(2, user.getUserPwd());
pt.setString(3, user.getUserSex());
pt.setString(4, user.getUserbornDate());
pt.setString(5, user.getUserEmail());
pt.setString(6, user.getUserAddress());
pt.setString(7, user.getUserPhoto());
pt.setString(8, user.getUserNickName());
result = pt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
ConnDB.close(null,pt,conn);
}
return result;
}
------解决方案--------------------
...
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306
/learn?zeroDateTimeBehavior=convertToNull", "root", "mysql");

if (conn != null) {
String sql = "select col_int, col_bigint, col_varchar, col_timestamp from type_test where id=1";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
rs.next();

int colInt = rs.getInt(1);
if (rs.wasNull()) {
System.out.println("col_int is null");
} else {
System.out.println(colInt);
}

long colBigint = rs.getLong(2);
if (rs.wasNull()) {
System.out.println("col_bigint is null");
} else {
System.out.println(colBigint);
}
System.out.println(rs.getString(3));
System.out.println(rs.getTimestamp(4));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}

if (stmt != null) {
stmt.close();
}

if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
...
给楼主参考一下,在使用JDBC操作数据库时,需要注意以下几点:
(1)异常的处理
(2)及时关闭ResultSet、Statement、PreparedStatement、Connection等资源。
  相关解决方案