由于第一个小程序就用到了关于spring的jdbc连接的问题,所以jdbc驱动,不用讲了,导吧。
表字段:表account---->id,userName,password
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/testdb"></property>
<property name="username" value="root"></property>
<property name="password" value="pass"></property>
</bean>
<bean id="login" class="AccountFind">
<property name="ds" ref="dataSource"></property>
</bean>
</beans>
AccountFind.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
public class AccountFind {
private DataSource ds;
public void setDs(DataSource ds) {
this.ds = ds;
}
public boolean isLogin(String userName, String password) {
try {
Connection conn = ds.getConnection();
String sql = "select userName,password from account where userName=? and password=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return true;
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
SpringTest.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args) {
// 很古老的加载方式
//Resource resource = new ClassPathResource("applicationContext.xml");
//BeanFactory factory = new XmlBeanFactory(resource);
ApplicationContext beanFactory = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AccountFind af = (AccountFind)beanFactory.getBean("login");
System.out.println(af.isLogin("brj", "是"));
}
}
去试试,行吧?