利用spring去连接数据库

本文介绍了如何通过Spring连接到MySQL数据库。首先创建数据库spring,然后在工程中建立com.SpringJdbc包,包含applicationContext.xml配置数据库连接,以及JdbcTemplateTest类。在配置文件中,特别提到url属性设置,避免出现字符集错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先桌面中“开始”栏中输出cmd
然后创建数据库spring
如下图:
在这里插入图片描述

输入mysql -uroot -p123456
(这里面-u后面的是用户名 -p是密码)

在这里插入图片描述
create database spring;(创建数据库spring)
use spring;(使用数据库spring)
show tables;(查看表)

在这里插入图片描述

在工程中建一个名为com.SpringJdbc的包,并在里面建立applicationCaontext.xml
和JdbcTemplateTest.class的两个文件
下列图为列:
在这里插入图片描述
applicationCaontext.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.xsd">
    <!--1.配置数据库-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <!--数据库驱动-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!--连接数据库url-->
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf-8" />
        <!--连接数据库的用户名-->
        <property name="username" value="root" />
        <!--连接数据库密码-->
        <property name="password" value="123456" />
    </bean>
    <!--2.配置JDBC模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--默认必须使用数据库-->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

注: property name=“url” value=“jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf-8”
?后面的不加characterEncoding=utf-8会有
Unknown initial character set index ‘255’ received from server. Initial client character
的错误

JdbcTemplateTest.class

package com.SpringJdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class JdbcTemliateTest {
    public static void main(String[] args) {
        //配置路径
        String xmlPath = "com/SpringJdbc/applicationContext.xml";
        //加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(xmlPath);
        //获取JdbcTemplate实例

        JdbcTemplate jdbcTemplate  =
                (JdbcTemplate) applicationContext.getBean("jdbcTemplate");

        //使用execute()方法执行sql语句,创建用户账号管理表account
        jdbcTemplate.execute("CREATE TABLE account("
                + "id INT PRIMARY KEY auto_increment,"
                + "username VARCHAR (50),"
                + "balance DOUBLE)");

        System.out.println("账户表account创建成功");

    }


}

在这里插入图片描述
然后去cmd中输入show tables;
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值