10个和数据库相关的Java程序设计经典例子
Posted zhulin1028
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了10个和数据库相关的Java程序设计经典例子相关的知识,希望对你有一定的参考价值。
为大家精心准备了上千本技术书籍,微信搜索关注公众号:【zhulin1028】,或者扫描以下二维码,回复【电子书】即可免费获取。
目录
例子8:使用预处理语句prepareStatement查询数据库
例子9:使用预处理语句prepareStatement增加、修改、删除、
例子1:使用jdbc-odbc桥读数据库
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
Statement stmt;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("" + e);
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM bookdata");
while (rs.next()) {
String isbn = rs.getString("isbn");
String name = rs.getString("name");
String authors = rs.getString(5);
float price = rs.getInt("price");
int pages = rs.getInt("pages");
System.out.print("书号:" + isbn);
System.out.print(" 书名:" + name);
System.out.print(" 作者:" + authors);
System.out.print(" 定价:" + price);
System.out.println(" 页数:" + pages);
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子2:条件查询
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
Statement stmt;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT name,price FROM bookdata WHERE price >= 30");
while (rs.next()) {
String name = rs.getString(1);
double price = rs.getInt("price");
System.out.print(" 书名:" + name);
System.out.println(" 定价:" + price);
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子3:可滚动结果集
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
Statement stat;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("" + e);
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
stat = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stat.executeQuery("SELECT name,pages FROM bookdata");
rs.last();
int number = rs.getRow();
System.out.println("该表共有" + number + "条记录");
rs.afterLast();
while (rs.previous()) {
String name = rs.getString("name");
int pages = rs.getInt("pages");
System.out.print(" 书名:" + name);
System.out.println(" 页数:" + pages);
}
System.out.println("单独输出第5条记录:");
rs.absolute(5);
String name = rs.getString("name");
int pages = rs.getInt("pages");
System.out.print(" 书名:" + name);
System.out.println(" 页数:" + pages);
rs.close();
stat.close();
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子4:排序结果集
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
Statement sql;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
sql = con.createStatement();
String condition = "SELECT name, pages FROM chengjibiao ORDER BY pages";
rs = sql.executeQuery(condition);
while (rs.next()) {
String name = rs.getString(1);
int pages = rs.getInt(2);
System.out.print(" 姓名:" + name);
System.out.println(" 页数:" + pages);
}
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子5:模糊查询
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
Statement sql;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book",
"123");
sql = con.createStatement();
rs = sql.executeQuery("SELECT name,price FROM bookdata WHERE name LIKE '%java%' ");
while (rs.next()) {
String name = rs.getString(1);
double price = rs.getInt(2);
System.out.print(" 书名:" + name);
System.out.println(" 定价:" + price);
}
rs.close();
sql.close();
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子6:计算抽样图书的平均页数。
import java.sql.*;
import java.util.LinkedList;
public class DatabaseTest {
public static void main(String args[]) {
LinkedList list = new LinkedList();
Connection con;
Statement sql;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = sql.executeQuery("SELECT name,pages FROM bookdata");
rs.last();
int lownumber = rs.getRow();
int number = lownumber;
for (int i = 1; i <= number; i++) {
list.add(new Integer(i));
}
double sum = 0;
int k = 4;
int 抽取数目 = k;
while (k > 0) {
int i = (int) (Math.random() * list.size());
int index = ((Integer) list.get(i)).intValue();
rs.absolute(index);
System.out.print("书名:" + rs.getString(1));
System.out.println("页数:" + rs.getString(2));
int math = rs.getInt("pages");
sum = sum + math;
k--;
list.remove(i);
}
System.out.println("抽样的图书平均页数:" + sum / 抽取数目);
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子7:图书信息的增加、修改、删除、查询。
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
Statement stmt;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book",
"123");
stmt = con.createStatement();
int pages = 299;
String isbn = "9877811234169", name, authors, publisher;
String updateStr = "UPDATE bookdata SET pages =" + pages
+ " WHERE isbn = " + "'" + isbn + "'";
pages = 400;
float price = 45.8f;
isbn = "9877811239999";
name = "Java高级数据库编程";
authors = "张三,李四,王五";
publisher = "蓝天出版社";
String value = "(" + "'" + isbn + "', '" + name + "', '" + authors
+ "', '" + publisher + "', " + pages + "," + price + ")";
String insertStr = "INSERT INTO bookdata(isbn, name, authors, publisher, pages, price) VALUES " + value;
String delStr = "DELETE FROM bookdata WHERE isbn = '9877811239999' ";
stmt.executeUpdate(updateStr);
stmt.executeUpdate(insertStr);
stmt.executeUpdate(delStr);
rs = stmt.executeQuery("SELECT * FROM bookdata");
while (rs.next()) {
isbn = rs.getString("isbn");
name = rs.getString("name");
authors = rs.getString(5);
publisher = rs.getString("publisher");
pages = rs.getInt("pages");
price = rs.getFloat("price");
System.out.print("书号:" + isbn);
System.out.print(" 书名:" + name);
System.out.print(" 作者:" + authors);
System.out.print(" 作者:" + publisher);
System.out.print(" 页数:" + pages);
System.out.println(" 定价:" + price);
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子8:使用预处理语句prepareStatement查询数据库
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
PreparedStatement pstmt;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("" + e);
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
pstmt = con.prepareStatement("SELECT isbn, price FROM bookdata"); // 预处理语句
rs = pstmt.executeQuery();
while (rs.next()) {
String isbn = rs.getString(1);
float price = rs.getFloat(2);
System.out.print("书号:" + isbn);
System.out.println(" 定价:" + price);
}
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子9:使用预处理语句prepareStatement增加、修改、删除、
import java.sql.*;
public class DatabaseTest {
public static void main(String args[]) {
Connection con;
PreparedStatement pstmt1, pstmt2, pstmt3;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("" + e);
}
try {
con = DriverManager.getConnection("jdbc:odbc:library", "book", "123");
pstmt1 = con.prepareStatement("UPDATE bookdata SET price = ? WHERE id= ? ");
pstmt1.setFloat(1, 55.5f);
pstmt1.setInt(2, 1);
pstmt1.executeUpdate();
pstmt1.setInt(1, 2);
pstmt1.setFloat(2, 66.6f);
pstmt1.executeUpdate();
pstmt2 = con.prepareStatement("INSERT INTO bookdata(isbn, name, pages, price) VALUES (?,?,?,?)");
pstmt2.setString(1, "20038881111");
pstmt2.setString(2, "Oracle数据库使用指南");
pstmt2.setInt(3, 300);
pstmt2.setFloat(4, 77.7f);
pstmt2.executeUpdate();
pstmt3 = con.prepareStatement("SELECT name, pages, price FROM bookdata WHERE pages <= ? AND price >= ? ");
pstmt3.setInt(1, 400);
pstmt3.setFloat(2, 50f);
System.out.println("3.............");
rs = pstmt3.executeQuery();
while (rs.next()) {
System.out.print("书名:" + rs.getString(1));
System.out.print(" 页数:" + rs.getInt(2));
System.out.println(" 定价:" + rs.getFloat(3));
}
con.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
例子10:综合例子
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client
{
public static void main(String args[])
{ new QueryClient();
}
}
class QueryClient extends Frame
implements Runnable,ActionListener
{ Button connection,send;
TextField inputText;
TextArea showResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
QueryClient()
{ socket=new Socket();
Panel p=new Panel();
connection=new Button("连接服务器");
send=new Button("发送");
send.setEnabled(false);
inputText=new TextField(8);
showResult=new TextArea(6,42);
p.add(connection);
p.add(new Label("输入学号"));
p.add(inputText);
p.add(send);
add(p,BorderLayout.NORTH);
add(showResult,BorderLayout.CENTER);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
setBounds(10,30,350,400);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==connection)
{ try
{ if(socket.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName("127.0.0.1");
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
socket.connect(socketAddress);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
}
}
catch (IOException ee){}
}
if(e.getSource()==send)
{ String s=inputText.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();
showResult.append("\\n"+s);
}
catch(IOException e)
{ showResult.setText("与服务器已断开");
break;
}
}
}
}
(2) 服务器端程序
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
public class Server
{ public static void main(String args[])
{ Connection con;
PreparedStatement sql=null;
ResultSet rs;
try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e){}
try{ con=DriverManager.getConnection("jdbc:odbc:sun","gxy","123");
sql=con.prepareStatement("SELECT * FROM chengjibiao WHERE number = ? ");
}
catch(SQLException e){}
ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println("正在监听");
}
try{ System.out.println(" 等待客户呼叫");
you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch(IOException e)
{ System.out.println("正在等待客户");
}
if(you!=null)
{ new Server_thread(you,sql).start();
}
}
}
}
class Server_thread extends Thread
{ Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
PreparedStatement sql;
boolean boo=false;
Server_thread(Socket t, PreparedStatement sql)
{ socket=t;
this.sql=sql;
try { out=new DataOutputStream(socket.getOutputStream());
in=new DataInputStream(socket.getInputStream());
}
catch(IOException e){}
}
public void run()
{ while(true)
{try{
String num=in.readUTF();
boo=false;
sql.setString(1,num);
ResultSet rs=sql.executeQuery() ;
while(rs.next())
{ boo=true;
String number=rs.getString(1);
String name=rs.getString(2);
String date=rs.getString(3);
int math=rs.getInt(4);
int english=rs.getInt(5);
out.writeUTF("学号:"+number+" 姓名:"+name+" 出生:"+date
+" 数学:"+math+" 英语"+english);
}
if(boo==false)
{ out.writeUTF("没有该学号!");
}
}
catch (Exception e)
{ System.out.println("客户离开"+e);
return;
}
}
}
}
以上是关于10个和数据库相关的Java程序设计经典例子的主要内容,如果未能解决你的问题,请参考以下文章
Java中基本数据类型的存储方式和相关内存的处理方式(java程序员必读经典)
背水一战 Windows 10 (76) - 控件(控件基类): Control - 基础知识, 焦点相关, 运行时获取 ControlTemplate 和 DataTemplate 中的元素(代码片