1..写简单sql语句执行
DROP TABLE IF EXISTS `jdbctest`; CREATE TABLE `jdbctest` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of jdbctest -- ---------------------------- INSERT INTO `jdbctest` VALUES (‘1‘, ‘tom‘); INSERT INTO `jdbctest` VALUES (‘2‘, ‘marry‘); INSERT INTO `jdbctest` VALUES (‘3‘, ‘kill‘);
2.写jdbc操作数据库代码(记得导入 mysql-connector-java-5.1.7-bin包)
package com.newbe.jdbc1; import java.sql.*; /** * @Auther: Newbe * @email:1160285648@qq.com * @Date: 2019/9/2 22:27 * @Description:个人手写jdbc */ public class MyJDBC { //定义数据库连接四要素:驱动名,url,用户名和密码 private static String Driver="com.mysql.jdbc.Driver"; private static String Url="jdbc:mysql://localhost:3306/test"; private static String UserName="root"; private static String PassWord="1234567"; public static void main(String[] args) { try { //1.加载jdbc驱动 Class.forName(Driver); //2.获取数据库连接 Connection connection = DriverManager.getConnection(Url,UserName, PassWord ); //3.获取预处理对象 String sql = "select * from JDBCTest"; PreparedStatement statement = connection.prepareStatement(sql); //4.执行sql语句 ResultSet result=statement.executeQuery(); //5.获取结果集取数据 System.out.println("id"+" "+"name"); while (result.next()){ int id=result.getInt("id"); String name=result.getString("name"); System.out.println(id+" "+name); } System.out.println(); //6.关闭连接 result.close(); statement.close(); connection.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { } } }
3.运行结果
原文:https://www.cnblogs.com/fby698/p/11450562.html