java教程

JDBC连接数据库方式(区别于mybatis方式)

位置:首页 > java教程 > java技巧,2019-07-30 22:41
Java连接MySql插入数据的代码package com.chendan.maven;import java.sql.Connection;import ja

Java连接MySql插入数据的代码


package com.chendan.maven;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class MavenTest {
    public static void main(String[] args) throws Exception {
        String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
        String url = "jdbc:mysql://10.0.0.30:3306/test?&useSSL=false"; // 连接数据库(test是数据库名)
        String user = "chendan";// 连接mysql的用户名
        String password = "123456";// 连接mysql的密码
        String insertsql = "insert into t1 values(?,?)";
        String querysql = "select * from t1";

        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        conn.setAutoCommit(false);
        PreparedStatement statement = conn.prepareStatement(insertsql);
        statement.setInt(1, 1);
        statement.setString(2, "Tom");

        statement.executeUpdate();
        conn.commit();

        ResultSet rst = statement.executeQuery(querysql);
           while (rst.next()) {
                System.out.println(rst.getInt(1) + "\t" + rst.getString(2));
            }

    }

}


TAGS:JDBC连接数据库

猜你喜欢

NewHot