Python和java(spring) 连接数据库的模板

发布于 2022-05-12  863 次阅读


Springboot连接数据库

1.maven引入包

<dependency>
   <groupId>com.microsoft.sqlserver</groupId>
   <artifactId>mssql-jdbc</artifactId>
   <version>7.4.1.jre8</version>
</dependency>

2.初始化application.yml

spring:
  datasource:
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    url: jdbc:sqlserver://服务器IP:1433;DatabaseName=默认数据库
    username: sa
    password: sa的密码

3.自动装配一个jdbc类

@Controller
public class testController {
    @Autowired
    JdbcTemplate jdbc=new JdbcTemplate();
    @RequestMapping("test")
    @ResponseBody
    public String test(){
        String sql="select * from sub_log";
        List<?> ans=jdbc.queryForList(sql);
        return ans.toString();
    }
}

JDBC直连数据库

Connection conn = null;
                Statement stmt = null;
                ResultSet rs = null;
                int rs1 = 0;
                try {
                    Class.forName("org.mariadb.jdbc.Driver");
                    conn = DriverManager.getConnection("jdbc:sqlserver://服务器IP:1433;DatabaseName=默认数据库", "sa", "密码");
                    stmt = conn.createStatement();
                    String sql = "UPDATE user_info set wintime=wintime+1 where name ='" + name + "'";
                    rs1 = stmt.executeUpdate(sql);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    if (stmt != null) {
                        try {
                            stmt.close();
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                }
            }

Python连接数据库

import pymssql


def queryForList(sql):
    conn = pymssql.connect(host='服务器IP', port='1433', user='sa', password='密码',
                           database='默认数据库')
    cur = conn.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    cur.close()
    conn.close()
    return data


queryForList("select * from 学生")

绝对不是恋爱脑!