java 查询带参数数据库_java操作Access数据库(带参数插入及查询)

最近使用了Acess数据库:

1、建好数据库

2、配好数据源

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.*;

import java.util.Properties;

/**

*

* @author Administrator

* @param 连接Acess数据库

*

*/

public class AcessL {

/**

* @param 返回连接方法

* @return Connection

*/

public static Connection getPre(){

Connection conn=null;

Properties p=new Properties();

try {

p.load(new FileInputStream("H:/YLZX/JWC/user.properties"));//读取文件中的数据,也可以直接写

Class.forName(p.getProperty("driver"));

conn=DriverManager.getConnection(p.getProperty("url"),p.getProperty("user"), p.getProperty("psw"));

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return conn;

}

/**

* @param 带参数的插入方法

* @param UserID

* @param UserPsw

* @param Type

*/

public void insert(String UserID,String UserPsw,String Type)

{

Connection conn=getPre();

try {

//Statement smt=conn.createStatement();

String sql="INSERT into User(UserID,UserPsw,type) values(?,?,?);";//sql语句中末尾的分号可有可无

PreparedStatement ppst=conn.prepareStatement(sql);

ppst.setString(1, UserID);//对sql语句中的每个?按顺序赋值,赋值的方法取决于数据库的字段属性,我的字段属性都是字符串类型

ppst.setString(2, UserPsw);

ppst.setString(3, Type);

ppst.executeUpdate();

System.out.println(sql);

//smt.close();

ppst.close();

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* @param 带参数的查询方法

* @param UserID

* @param UserPsw

* @param Type

* @return

*/

public boolean Select(String UserID,String UserPsw,String Type){

boolean bool=false;

Connection conn=getPre();

PreparedStatement ppst=null;

ResultSet rs=null;

String s=" ";

String sql="select UserPsw from User where UserID=? and type=?";

try {

ppst=conn.prepareStatement(sql);

ppst.setString(1, UserID);

ppst.setString(2, Type);

rs=ppst.executeQuery();

while(rs.next())

{

s=rs.getString(1);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

rs.close();

ppst.close();

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

if(s.equals(UserPsw))

{

bool=true;

}

else{

bool=false;

}

return bool;

}

public static void main(String args[])

{

AcessL acessl=new AcessL();

//System.out.println(acessl.getPre());

//acessl.insert("LB90aaaa","9090","1");

System.out.println(acessl.Select("L", "89", "0"));

}

}


版权声明:本文为weixin_28941895原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。