import java.sql.DriverManager
import java.sql.SQLException
public class ConnectionDemo{
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver"
// 定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn"
// MySQL数据库的连接用户名
public static final String DBUSER = "root"
// MySQL数据库的连接密码
public static final String DBPASS = "mysqladmin"
public static void main(String args[]){
Connection conn = null // 数据库连接
try{
Class.forName(DBDRIVER) // 加载驱动程序
}catch(ClassNotFoundException e){
e.printStackTrace()
}
try{
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS)
}catch(SQLException e){
e.printStackTrace()
}
System.out.println(conn) // 如果此时可以打印表示连接正常
try{
conn.close() // 数据库关闭
}catch(SQLException e){
e.printStackTrace()
}
}
}
通过配置文件<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.ijava.springmvc.dao"/>
<!-- 加载配置文件 --> <!-- placeholder 占位符 -->
<context:property-placeholder location="classpath:resources/db.properties"/>
<!-- 数据库连接池 -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 创建对象 -->
<bean id="userDao" class="com.ijava.springmvc.dao.UserDaoImpl"></bean>
<bean id="userService" class="com.ijava.springmvc.service.UserServiceImpl"></bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
</beans>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)