java数据库编程1

1、连接数据库的基本步骤:steps

2、执行数据库的插入,修改,更新,删除操作。以及对预处理操作PreparedStatement接口的查询选择操作。

代码如下:

package org.lxh.demo17.connectdemo;

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;
import java.sql.ResultSet;  
import java.sql.Statement;

//import java.sql.SQLException;  
//import java.sql.Statement;  

public class ConnectionDemo01{
	public static void main(String[]args)throws Exception{
		try{
			Class.forName("org.gjt.mm.mysql.Driver");

			try{
				
			Connection connection =  DriverManager.getConnection("jdbc:mysql://localhost:3306/class2", "root", "1234");
			Statement statement = connection.createStatement();	 
			
			PreparedStatement pstmt=connection.prepareStatement("SELECT id,name,sex,age FROM stu WHERE id LIKE ? OR name LIKE ? OR sex LIKE ? OR age LIKE ?");
			
		 //   statement.executeUpdate("INSERT INTO stu (id,name,sex,age)" + " VALUES ('5','lucy1','F','20' )");
			
		  pstmt.setString(1,"%"+"l"+"%");
		  pstmt.setString(2,"%"+"l"+"%");
		  pstmt.setString(3, "%"+"l"+"%");//select中有几个问号在这里就要加上几个setString。
		  pstmt.setString(4,"%"+"l"+"%");
		  
		  ResultSet rs=pstmt.executeQuery();
		  
		  while(rs.next()){
			  int id=rs.getInt(1);
			  String name=rs.getString(2);
			  String sex=rs.getString(3);
			  int age=rs.getInt(4);			 	  
		 	    
		  //  ResultSet resultSel = statement.executeQuery( "select * from stu" );
		 //   while(resultSel.next()){
		    	/*int id=resultSel.getInt("ID");
		    	String name=resultSel.getString("name");
		    	String sex=resultSel.getString("sex");
		    	int age=resultSel.getInt("age");*/
		    	
		  //  	int id=resultSel.getInt(1);
		   // 	String name=resultSel.getString(2);
		   // 	String sex=resultSel.getString(3);
		  //  	int age=resultSel.getInt(4);
		    	
		    	System.out.print("学号:"+id+"; \n");
		    	System.out.print("姓名:"+name+"; \n");
		    	System.out.print("性别"+sex+";\n ");
		    	System.out.print("年龄"+age+"; \n");	    	
		    }
		   // statement.executeUpdate("update stu set age=30 where name='lily'");
		   statement.executeUpdate("delete from userclob where name='lily'");
		    
		    //resultSel.close();
		    //statement.close(); 
		    //connection.close();
		  rs.close();
		  pstmt.close();
		  connection.close();		    
			}
			catch (Exception e) {
				System.out.println("数据库连接失败" + e.getMessage());  
				// TODO: handle exception
			}
			
			System.out.println("success");
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
				}
}

 3、处理大数据对象(写入和读取操作)的代码还在测试中,其中输出文件的内容到测试console中显示时有问题。

posted on 2013-09-03 21:15  lyeoswu  阅读(181)  评论(0编辑  收藏  举报

导航