在Java中如何对数据库中的数据进行操作?

增删改查数据的具体代码... 增删改查数据的具体代码 展开
 我来答
匿名用户
2013-08-28
展开全部
package com.dao;import java.sql.*;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;public class BaseDao {
/**
* 创建数据库连接及关闭
*/
// 打开连接
public static Connection getConnection() {
Connection con = null; /*************************** oracl 的连接 ***************************************/
// try { // Class.forName("oracle.jdbc.driver.OracleDriver");
// con = DriverManager.getConnection(
// "jdbc:oracle:thin:@127.0.0.1:1521:orcl", "bbs", "sa");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// }
/******************************* sqlerver 的连接 ******************************/
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://127.0.0.1:1433;databasename=bbs", "sa",
"zhou");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
/*********************************************************************/
return con;
} // 关闭
public static void closeAll(Connection connection,
PreparedStatement pStatement, ResultSet res) {
try {
if (connection != null && (!connection.isClosed())) {
connection.close();
}
if (res != null) {
res.close();
res = null;
}
if (pStatement != null) {
pStatement.close();
pStatement = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
对数据库增删改查package com.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;import com.entity.News;public class NewsDao {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

/**
* 添加新闻
* @param news
* @return
*/
public boolean newsAdd(News news){
boolean result=false;
String sql="insert into news values(?,?)";
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
pstmt.setString(1, news.getContent());
pstmt.setString(2, FormatTime.newTime());

int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 修改新闻
* @param news
* @return
*/
public boolean updateNews(News news){
boolean result=false;
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement("update news set content=? ,writedate=? where newsid=?");
pstmt.setString(1, news.getContent());
pstmt.setString(2, FormatTime.newTime());
pstmt.setInt(3, news.getNewsID());
int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 删除新闻
* @param news
* @return
*/
public boolean deleteNews(News news){
boolean result=false;
String sql=String.format("delete from news where newsid=%d", news.getNewsID());
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);

int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

/**
* 删除新闻 重载
* @param newsId
* @return
*/
public boolean deleteNews(int newsId){
boolean result=false;
String sql=String.format("delete from news where newsid=%d", newsId);
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 查询所有的新闻
* @return
*/
public List<News> selectAllNews(){
List<News> list=new ArrayList<News>();
String sql="select * from Users";
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()){
News news=new News();
news.setNewsID(rs.getInt(1));
news.setContent(rs.getString(2));
news.setWriteDate(rs.getString(3));

list.add(news);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeAll(rs, pstmt, con);
}
return list;
}
/**
* 查询单个
* @return
*/
public News selectOneNews(){
News news=new News();
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement("select top 1 * from news order by newsid desc");
rs=pstmt.executeQuery();
while(rs.next()){
news.setNewsID(rs.getInt(1));
news.setContent(rs.getString(2));
news.setWriteDate(rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeAll(rs, pstmt, con);
}
return news;
}

}
实体类package com.entity;import java.io.Serializable;
public class News implements Serializable{
private int newsID;
private String content;
private String writeDate; public News() {
super();
// TODO Auto-generated constructor stub
} public News(String content, String writeDate) {
super();
this.content = content;
this.writeDate = writeDate;
} public News(int newsID, String content, String writeDate) {
super();
this.newsID = newsID;
this.content = content;
this.writeDate = writeDate;
} public int getNewsID() {
return newsID;
} public void setNewsID(int newsID) {
this.newsID = newsID;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public String getWriteDate() {
return writeDate;
} public void setWriteDate(String writeDate) {
this.writeDate = writeDate;
}
}
匿名用户
2013-08-28
展开全部
//此类为连接数据库并进行数据库的操作
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Conn {
private static Connection conn = null;
private static Statement st = null;
private static ResultSet rs = null;
//建立数据库的连接
public Conn(){
String url = "jdbc:sqlserver://localhost:1433;databaseName=ZYGX";
String user = "sa";
String password = "123";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, user, password);
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

// 通过不同 的sql语句,得到相应Resultset结果集
public ResultSet getRs(String sql){
try{
rs= st.executeQuery(sql);
}catch(SQLException e){
e.printStackTrace();
}
return rs;
}
// 根据不同的sql语句,执行数据库的更新操作
public int updata(String sql){
int num=0;
try{
num = st.executeUpdate(sql);
}catch(SQLException e){
e.printStackTrace();
}
return num;
}
// 关闭数据库连接相应的资源
public void close(){
try{
if(rs!=null){
rs.close();
rs = null;
}
if(st!=null){
st.close();
st = null;
}
if(conn!=null){
conn.close();
conn = null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
----------------------------------------------------------------------
//可以对button里添加动作按钮:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Conn conn =new Conn();
String sql1="select * from aa where name='"+name+"' ";//按name值查找
ResultSet rs = conn.getRs(sql1);
try {
while(rs.next()){
int n=rs.getString("type");
}
} catch (SQLException e) {
e.printStackTrace();
}
String name=textField.getText();
String sql="update aa set tittle='"+name+"' ";//从aa表将title字段的值改成textField里的name值
String sql2 ="delete from aa where name='"+name+"'";//从aa表将按取得name的值删除该行数据
String sql3 = "insert into aa (name,uname) values ('"+name+"','"')"; //将name,uname值新增到aa表
if(conn.update(sql)==1){
System.out.print("修改成功");
}
if(conn.update(sql2)==1){
System.out.print("删除成功");
}
if(conn.update(sql3)==1){
System.out.print("新增成功");
}
}
});
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
沫神钢虚1F
2017-01-16 · TA获得超过2.4万个赞
知道大有可为答主
回答量:1.6万
采纳率:59%
帮助的人:1114万
展开全部
1.提取单条记录
//import java.sql.*;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:%%1";
con=DriverManager.getConnection(url,%%2,%%3);
stmt=conn.createStatement();
stmt.executeUpdate(%%4);
rs=stmt.executeQuery(%%5);
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

3.显示表格
/*
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.table.*;
*/
String[] colHeads=%%4;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:%%1";
conn=DriverManager.getConnection(url,%%2,%%3);
stmt=conn.createStatement();
rs=stmt.executeQuery("SELECT count(*) as au_count from "+%%5);
rs.next();
int iCount=rs.getInt("au_count");
Object[][] data=new Object[iCount][];
int i=0;
rs=stmt.executeQuery("SELECT * from "+%%5);
while(rs.next()){
data[i]=new Object[iCount];
data[i][0]=rs.getString("au_fname");
data[i][1]=rs.getString("Phone");
data[i][2]=rs.getString("City");
i++;
}
JTable table=new JTable(data,colHeads);
JScrollPane jsp=new JScrollPane(table);
getContentPane().add(jsp);
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
6.关闭时关闭连接
//import java.sql.*;
addWindowListener(new WindowAdapter{
public void windowClosing(WindowEvent wevent){
if(stmt!=null){
try {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

7.执行命令
//import java.sql.*;
Connection conn=null;
PreparedStatement pst=null;
try {
conn=DriverManager.getConnection(url);
pst=conn.prepareStatement("Insert Into grade(%%1) Values (?)");
pst.setInt(1,%%2);
//pst.setString(2,%%2);
pst.addBatch();
pst.executeBatch();
} catch (SQLException e){
e.printStackTrace();
}
finally{
try {
if (pst != null)
pst.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式