简介
java连接数据库并实现增删改基本功能
代码
package com.xiaoruanzi.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
Connection cn = null;
Statement statement = null;
try {
// 2.连接数据库
// jdbc:mysql://ip:port/数据库实例名
String url = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "root";
cn = DriverManager.getConnection(url, user, password);
System.out.println(cn);
// 3.获取statement对象,用来向mysql发送sql语句的
statement = cn.createStatement();
// 4.执行sql语句
// String sql = "insert into user(uname,money) values('tom123',6000)";
// String sql = "update user set money=10000 where uname='jack'";
String sql = "delete from user where uname='tom123'";
statement.executeUpdate(sql);// executeUpdate():出力敏感操作
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 5.关闭连接
try {
statement.close();
cn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
总结
5个步骤