天天看点

spring中的mysql数据库_spring中操作mysql数据库

就是在spring中,对mysql数据库进行增删改查的样例,很easy。

文件结构

spring中的mysql数据库_spring中操作mysql数据库

maven的pom.xml文件,里面用到的几个很重要的jar包都有

4.0.0

MySpring

MySpring

0.0.1-SNAPSHOT

MySpring

MySpring

org.springframework

spring-context

4.1.0.RELEASE

org.springframework

spring-jdbc

4.1.0.RELEASE

mysql

mysql-connector-java

5.0.5

操作类

package nx.database;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.sql.DataSource;

public class StudentsDaoImpl implements StudentsDao{

private DataSource dataSource;

public DataSource getDataSource() {

return dataSource;

}

public void setDataSource(DataSource dataSource) {

this.dataSource = dataSource;

}

public void saveStudents() {

Connection conn=null;

PreparedStatement stmt=null;

try {

conn=dataSource.getConnection();

stmt=conn.prepareStatement("INSERT INTO `data`.`student` (`id`, `name`) VALUES (NULL, 'jiang');");

stmt.execute();

stmt.close();

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("保存学生信息成功。");

}

}

beans.xml(注意,数据库的password替换成你自己的password)

>

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.5.xsd">

測试类

package nx.database;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {

// TODO Auto-generated method stub

ApplicationContext ctx=new ClassPathXmlApplicationContext("nx/database/beans.xml");

StudentsDaoImpl userImpl=(StudentsDaoImpl)ctx.getBean("userImpl");

userImpl.saveStudents();

}

}

在完毕后,查看数据库,发现已经有了数据

spring中的mysql数据库_spring中操作mysql数据库