JDBC编程示例

package com.lovo.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import com.lovo.bean.ClassBean;

public class TestDML {

public static void main(String[] args) {
String className = JOptionPane.showInputDialog("请输入班级名字");
String teacherName = JOptionPane.showInputDialog("请输入班主任名字");

//数据库操作步骤:
//1、加载驱动---告诉驱动管理器我们将使用哪一个数据库的驱动包
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//2、操作JDBC API完成数据库动作
//2-1、获取连接
Connection con = null;
try {
//url--统一资源定位符----样式:协议://ip地址:端口号/服务
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test134" +
"?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "root");
//2-2、书写SQL语句---字符串拼接、
String sql = "insert into t_class(f_classname,f_teacher) values('"+className+"','"+teacherName+"')";
//2-3、获取语句对象---Statement对象
Statement state = con.createStatement();
//2-4、执行语句对象---所有的DML语句,全部执行executeUpdate()方法
int row = state.executeUpdate(sql);//返回的int代表影响了多少行!
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//2-5、关闭连接
if(con != null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}










}
}

原文地址:https://www.cnblogs.com/fengshaolingyun/p/6785123.html