JAVA程序和数据库的连接和交互操作

一、最原始的直接连接

package com.java1234.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbUtil {
	private String dbUrl="jdbc:mysql://localhost:3306/bcm"; // 数据库连接地址
	private String dbUserName="root"; // 用户名
	private String dbPassword="root123456"; // 密码
	private String jdbcName="com.mysql.jdbc.Driver"; // 驱动名称
	 
	/**
	 * 获取数据库连接
	 * @return
	 * @throws Exception
	 */
	public Connection getCon()throws Exception{
		Class.forName(jdbcName);
		Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
		return con;
	}
	/**
	 * 关闭数据库连接
	 * @param con
	 * @throws Exception
	 */
	public void closeCon(Connection con)throws Exception{
		if(con!=null){
			con.close();
		}
	}
	
	public static void main(String[] args) {
		DbUtil dbUtil = new DbUtil();
		try {
			dbUtil.getCon();
			System.out.println("数据库链接成功 ");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("数据库链接失败 ");

		}
	}
}

在使用处调用连接、关闭连接方法即可:

查询:

public class UserDao {
	public User login(Connection con,User user)throws Exception{
		User resultUser = null;
		String sql = "select * from t_user where userName=? and password=? ";
		
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1,user.getUserName());
		pstmt.setString(2,user.getPassword());
		ResultSet rs=pstmt.executeQuery();
		if(rs.next()){
			resultUser=new User();
			resultUser.setId(rs.getInt("id"));
			resultUser.setUserName(rs.getString("userName"));
			resultUser.setPassword(rs.getString("password"));
		}
		return resultUser;
	}
}

修改:

	public int add(Connection con,Book book)throws Exception{
		String sql="insert into t_book values(null,?,?,?,?,?,?)";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setString(1, book.getBookName());
		pstmt.setString(2, book.getAuthor());
		pstmt.setString(3, book.getSex());
		pstmt.setFloat(4, book.getPrice());
		pstmt.setInt(5, book.getBookTypeId());
		pstmt.setString(6, book.getBookDesc());
		return pstmt.executeUpdate();
		
	}
	public int update(Connection con,Book book)throws Exception{
		String sql="update t_book set bookName=?,author=?,sex=?,price=?,bookDesc=?,bookTypeId=? where id=?";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setString(1, book.getBookName());
		pstmt.setString(2, book.getAuthor());
		pstmt.setString(3, book.getSex());
		pstmt.setFloat(4, book.getPrice());
		pstmt.setString(5, book.getBookDesc());
		pstmt.setInt(6, book.getBookTypeId());
		pstmt.setInt(7, book.getId());
		return pstmt.executeUpdate();
	}

二、使用Tomcat连接池

1)在applicationContext.xml中配置连接

先引入:

xmlns:jee="http://www.springframework.org/schema/jee"
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd

配置jndi, 其中jndi-name名称需要和连接参数处一致。


	<!-- Database -->
	<jee:jndi-lookup id="dataSource"
					 jndi-name="jdbc/powerAppMdService"
					 cache="true"
					 resource-ref="true"
					 lookup-on-startup="false"
					 proxy-interface="javax.sql.DataSource"/>

2)在context.xml中配置 数据源:

context.xml 中增加数据源:

   <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver"
              maxActive="20" maxIdle="3"
              name="jdbc/powerAppMdService" password="root123456"
              type="javax.sql.DataSource"
              url="jdbc:mysql://localhost:3306/bcm?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true"
              username="root"/>

context.xml 这个文件,一般可以放这几个地方:

第一种:将context.xml文件 放到运行的Tomcat/conf 目录下,直接可以使用。但是在项目打包部署到生产环境的时候需要注意修改配置服务器上tomcat的conf中context.xml

第二种:放在web项目中的META-INF下目录下,这种方式优点就是部署的时候不用管数据库的连接配置。ideal 使用这种方式,需要在 facets 上配置,很简单的配置, 下面方法截图

第三种:是使用eclipse的,在eclipse中项目运行tomcat的 servers目录下。这种方式和第一种差不多。又比第一种灵活点。

3)剩下的就是怎么使用了。写一个之前使用过的 jdbcTemplate的方式。

先声明一个jdbcTemplate:

private JdbcTemplate jdbcTemplate;

然后通过注解@Autowired 在类加载的时候初始化,dataSource为applicationContext.xml中配置的id(根据不同id,一个项目可以配置多个数据源,在此处根据需要初始化不通的数据源的JdbcTemplate):

@Autowired
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

具体代码:

@Component
public class UserLoginService {

    private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public User getUser(String userId, String password) {
        try {
            final Object[] obj = new Object[]{userId, password};
            return this.jdbcTemplate.queryForObject("select * from OSP.MD_SYS_USER where userId=? and password=?", obj, new BeanPropertyRowMapper<User>(User.class));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

org.springframework.jdbc.core.JdbcTemplate 中还又许多查询,修改操作,根据不同方法返回需要的结果。 

这些都是以前做过的项目使用过的,好久不用,随着时间的推移慢慢的遗忘了。

现在忽然工作节奏慢,有时间了,在这里做一个总结,方便自己复习。 也希望能帮助有需要的朋友。

发布了49 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/shenju2011/article/details/96835933