怎么在Java中往数据库表插入新的内容

怎么在Java中往数据库表插入新的内容,第1张

(1)传统方式

持久化数据库对象 —— 表 如:Hibernate等;

//保存一个数据库对象

public boolean saveEntity(Object entity) {

try {

getHibernateTemplate().save(entity)

return true

} catch (Exception e) {

e.printStackTrace()

}

return false

}

(2) 直接SQL语句插入

如:insert into ......

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()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/10864024.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-11
下一篇 2023-05-11

发表评论

登录后才能评论

评论列表(0条)

保存