1.第一种写法
package com.woniuxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载驱动:底层使用反射创建JDBC实现类对象
//className---当前数据库的核心实现类驱动类的全限定名
Class.forName("com.mysql.cj.jdbc.Driver");
//使用DriverManager驱动管理器创建连接对象
//String url, jdbc:mysql://连接服务器的IP地址:端口号/数据库名
//String user, 数据库账号
//String password, 数据库密码
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "123");
//创建Statement对象,用来执行sql语句
Statement statement=connection.createStatement();
//定义sql语句
String sql="insert into student values(1,'zs',11)";
//增删改都用这个方法executeUpdate(),返回受影响的行数
int count =statement.executeUpdate(sql);
System.out.println("count="+count);
//关闭资源
statement.close();
connection.close();
}
}
2.第二种写法
package com.woniuxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Comparator;
import java.util.Scanner;
public class Test02 {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "123");
Statement statement= connection.createStatement();
System.out.println("请输入学号");
int id = scanner.nextInt();
System.out.println("请输入姓名");
String name = scanner.next();
System.out.println("请输入年龄");
int age = scanner.nextInt();
String sql="insert into student values("+id+",'"+name+"',"+age+")";
System.out.println(sql);
statement.executeUpdate(sql);
statement.close();
connection.close();
}
}
标签:java,String,数据库,idea,connection,statement,sql,import From: https://www.cnblogs.com/huangjiangyang/p/16967222.html