java连接数据库查询

时间:2025-04-27 09:07:58

对整个表进行查询并输出

package text;
import .*;
import ;
import ;
public class Demo2 {
	public static void main(String args[]) {
		String URL="jdbc:mysql://localhost:3306/db";    
   	 String USER="root";
   	 String PASSWORD="root";   
   	 Statement sta=null;
   	 Connection con=null;
   	 ResultSet rs =null;
   	try {
		("");
		con=(URL,USER,PASSWORD);
		sta =();
		String sql="select * from s ";
		rs =(sql);
		while(()) {
			int id=("id");
			String name=("name");
			int age =("age");
			(id+"-->"+name+"-->"+age);
		}
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		();
	}
   	finally {
   		if(rs!=null)
   		try {
			();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			();
		}
   		if(sta!=null)
			try {
				();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				();
			}
   		if(con!=null)
			try {
				();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				();
			}
   	}
	}
}

对输入的用户名密码进行查询与表中原有的进行比对

package text;
import .*;
import ;
import ;
public class Demo4 {
	 String URL="jdbc:mysql://localhost:3306/db";    
	 String USER="root";
     String PASSWORD="root";   
	public void login(){
		 Statement sta=null;
	   	 Connection con=null;
	   	 ResultSet rs =null;
			try {
				("");
				con=(URL, USER, PASSWORD);
				sta =();
				Scanner sc=new Scanner();
				("请输入用户名:");
				String u=();
				("请输入密码:");
				String paw=();
				String sql="select count(*) from text where username='"+u+"' and password='"+paw+"'";
				rs=(sql);
				int count =-1;
				while(()) {
					count=(1);
				}
				 if(count>0)
	         	("login succe!");
	             else
	         	 ("login error!");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				();
			}
            catch (SQLException e) {
				// TODO Auto-generated catch block
				();
			}
	}
	public static void main(String args[]) {
		Demo4 d =new Demo4();
		();
	}
}