Java简单数据库操作
本示例实现Java插入和查询数据。
1. 建立与数据库连接类DbTool(本实例是Java与SQL Server 2008),代码如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DbTool { private static Connection conn=null; //创建Connection对象 public static Connection getConn() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //加载SQL Server数据库驱动 } catch(ClassNotFoundException e) { e.printStackTrace(); } //指定连接数据库的URL String url="jdbc:sqlserver://localhost:1433;databaseName=SRM"; String user="sa"; //指定连接数据库的用户名 String passWord="1111"; //指定连接数据库的密码 try { conn=DriverManager.getConnection(url,user,passWord); if(conn!=null) { //如果Connection实例不为空 //System.out.println("数据库连接成功"); //提示信息 } /* //加载MySQL数据库的连接 Class.forName("com.mysql.jdbc.Driver"); //加载MySQL数据库驱动 String url="jdbc:mysql://localhost:3306/SRM"; String user="sa"; String passWord="1111"; conn=DriverManager.getConnection(url,user,passWord); if(conn!=null){ } //加载Oracle数据库的连接 Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序 String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:SRM";// 127.0.0.1是本机地址,SRM是精简版Oracle的默认数据库名 String user = "sa";// 用户名 String password = "1111";// 你安装时选设置的密码 conn = DriverManager.getConnection(url, user, password);// 获取连接 */ } catch(SQLException e) { e.printStackTrace(); } return conn; } }
2. 创建数据操作类,代码如下:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; public class DbOperation { private static DbOperation instance = null; public static DbOperation getInstance() { //返回DbOperation类实例的静态方法,单例模式!!!! if (instance == null) { instance = new DbOperation(); } return instance; } public boolean addTbNews(TbNews tns) { //添加数据方法 Connection conn=null; boolean result=false; try { conn=DbTool.getConn(); //建立与数据库的连接 String sqlInsert="INSERT INTO tbNews(topicId,contentTxt)VALUES(?,?)"; PreparedStatement stm=conn.prepareStatement(sqlInsert); stm.setString(1, tns.getTopicId()); stm.setString(2, tns.getContentTxt()); int i=stm.executeUpdate(); if (i==1) { result=true; } }catch(SQLException e) { e.printStackTrace(); }finally { try { conn.close(); }catch (SQLException e) { e.printStackTrace(); } } return result; } public Vector<TbNews> queryTbNews(){ //返回Vector类型方式查询数据 Vector<TbNews> list =new Vector<TbNews>(); Connection conn=null; try { conn=DbTool.getConn(); Statement stmt=conn.createStatement(); String querySql="select * from TbNews"; ResultSet rs=stmt.executeQuery(querySql); while(rs.next()) { TbNews tbs=new TbNews(); tbs.setTopicId(rs.getString(1)); tbs.setContentTxt(rs.getString(2)); list.add(tbs); } } catch(Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch(SQLException e) { e.printStackTrace(); } } return list; } public List<String> selectTbNews(){ //查询数据方法 List<String> tbsList=new ArrayList<String>(); Connection conn=null; try { conn=DbTool.getConn(); Statement stmt=conn.createStatement(); String selectSql="select * from TbNews"; ResultSet rs=stmt.executeQuery(selectSql); //执行SQL并返回结果集 while(rs.next()) { String tbs=rs.getString("topicId")+","+rs.getString("contentTxt"); tbsList.add(tbs); } } catch(Exception e) { e.printStackTrace(); } finally { try { conn.close(); //关闭连接 }catch(SQLException e) { e.printStackTrace(); } } return tbsList; } }
3. 创建实体类,代码如下:
public class TbNews { private String topicId; private String contentTxt; public String getTopicId() { return topicId; } public void setTopicId(String topicId) { this.topicId=topicId; } public String getContentTxt() { return contentTxt; } public void setContentTxt(String contentTxt) { this.contentTxt=contentTxt; } }
4. 创建主窗体(添加记录窗体),代码如下:
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class BoxLayoutFrame extends JFrame { private JTextField textField; private JTextArea textArea; public static void main(String[] args) { // TODO Auto-generated method stub BoxLayoutFrame frame=new BoxLayoutFrame(); frame.setVisible(true); } public BoxLayoutFrame() { super(); setTitle("箱式布局管理界面"); setBounds(360,260,360,320); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container cp=getContentPane(); Box topicBox=Box.createHorizontalBox(); //创建一个水平箱容器 cp.add(topicBox, BorderLayout.NORTH); //添加到窗体中的最北部 topicBox.add(Box.createHorizontalStrut(5)); //添加一个5像素的水平支柱 JLabel topicLabel=new JLabel("主题:"); //创建标签topicLabel topicBox.add(topicLabel); //添加到水平箱容器中 topicBox.add(Box.createHorizontalStrut(5)); //添加一个5像素的水平支柱 textField=new JTextField(80); //创建文本框 topicBox.add(textField); //添加到水平容器中 Box box=Box.createVerticalBox(); //创建一个垂直箱容器 cp.add(box, BorderLayout.CENTER); //添加到窗体中 box.add(Box.createVerticalStrut(5)); //添加一个5像素的垂直支柱 Box contentBox=Box.createHorizontalBox(); //创建一个水平箱容器 contentBox.setAlignmentX(1); //设置组件的水平调整值,靠右对齐 box.add(contentBox); //添加到垂直容器中 contentBox.add(Box.createHorizontalStrut(5)); //添加一个5像素的水平支柱 JLabel contentLabel=new JLabel("内容:"); //定义标签contentLabel contentLabel.setAlignmentY(0); //设置组件的垂直调整值,靠上方对齐 contentBox.add(contentLabel); //添加到水平箱容器中 contentBox.add(Box.createHorizontalStrut(5)); //添加一个5像素 JScrollPane scrollPane=new JScrollPane(); //创建滚动面板 scrollPane.setAlignmentY(0); //设置组件的垂直调整值,向上对齐 contentBox.add(scrollPane); //将滚动面板添加到contentBox中 textArea=new JTextArea(); //创建文本框textArea textArea.setLineWrap(true); //允许自动换行 scrollPane.setViewportView(textArea); //文本框添加到滚动面板scrollPane box.add(Box.createVerticalStrut(5)); //添加一个5像素高的垂直支柱 Box bottomBox=Box.createHorizontalBox(); bottomBox.setAlignmentX(1); box.add(bottomBox,BorderLayout.SOUTH); JButton viewButton=new JButton("浏览记录"); bottomBox.add(viewButton); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SelectFrame sframe=new SelectFrame(BoxLayoutFrame.this); sframe.setVisible(true); } }); JButton button=new JButton("确定"); //创建一个按钮button button.setAlignmentX(1); //设置组件的水平调整值,靠右对齐 //box.add(button); //按钮添加到垂直箱容器 bottomBox.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent arg1) { //System.exit(0); if(textField.getText().length()==0) {//如果文本框无输入信息则不作任何处理 } if(!textField.getText().equals("")) { TbNews tbs=new TbNews(); tbs.setTopicId(textField.getText()); tbs.setContentTxt(textArea.getText()); boolean res =DbOperation.getInstance().addTbNews(tbs); if (res==true) { textField.setText(null); textArea.setText(null); } } } }); } }
5. 创建浏览记录窗体,代码如下:
import java.awt.BorderLayout; import java.awt.Container; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.Vector; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SelectFrame extends JDialog { Thread t; private JTable table; private DefaultTableModel tableModel; public SelectFrame(BoxLayoutFrame frame) { super(frame,"浏览记录",true); setBounds(380,300,300,260); Container cp=getContentPane(); String[] columns= {"topicId","contentTxt"}; tableModel=new DefaultTableModel(columns,0); List<String> tbs=DbOperation.getInstance().selectTbNews(); for(String info:tbs) { String[] args=info.split(","); tableModel.addRow(args); } table=new JTable(); table.setModel(tableModel); final JScrollPane scrollPane=new JScrollPane(); cp.add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(table); } }
执行添加结果如下:
执行浏览记录结果如下图所示: