
文章插图

文章插图
package li.jdbc;import com.mysql.jdbc.Driver;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;/** * 这是第一个jdbc程序 , 完成简单的操作 */public class jdbc01 {public static void main(String[] args) throws SQLException {//前置工作:在项目下创建一个文件夹如 libs//将mysql.jar拷贝到该目录下 , 点击add to project.. 加入到项目中//1.注册驱动Driver driver = new Driver();//创建一个driver对象//2.得到连接/*** jdbc:mysql://是规定好的协议 , 表示通过jdbc的方式来连接mysql* localhost 表示要连接到的主机ip地址* 3306 表示mysql监听的端口* hsp_db02 表示连接到 mysql DBMS的哪个数据库*/// mysql的连接本质就是socket的连接String url = "jdbc:mysql://localhost:3306/hsp_db02";//将用户名和密码放入到一个Properties对象中Properties properties = new Properties();// user 和 password 是规定好的 , 后面的值根据实际情况写properties.setProperty("user", "root");//用户properties.setProperty("password", "123456");//密码Connection connect = driver.connect(url, properties);//3.执行sqlString sql = "insert into actor values(null,'刘德华','男','1970-11-11','110')";//String sql = "update actor set name ='周星驰' where id = 1 ";//String sql = "delete from actor where id = 1 ";//Statement 用于执行静态SQL语句并返回其生成的结果的对象Statement statement = connect.createStatement();int rows = statement.executeUpdate(sql);//如果是dml语句 , 返回的就是影响的行数System.out.println(rows > 0 ? "成功" : "失败");//4.关闭连接资源statement.close();connect.close();}}

文章插图
在SQL yog中执行语句查询 , 发现actor表中成功插入一条数据

文章插图
2.2数据库连接的5种方式2.2.1方式1
//获取Driver实现类对象Driver driver = new com.mysql.jdbc.Driver();String url = "jdbc:mysql://localhost:3306/jdbc_db";Properties info = new Properties();info.setProperty("user", "root");//用户info.setProperty("password", "123456");//密码Connection conn = driver.connect(url,info);System.out.println(conn);
2.2.2方式2方式1会直接使用com.mysql.jdbc.Driver()
, 属于静态加载 , 灵活性差 , 依赖性强方式2使用反射机制进行动态加载 , 而且信息可以放入配置文件中保存 , 更利于项目的控制

文章插图
例子
package li.jdbc;//分析java连接mysql的5种方式import com.mysql.jdbc.Driver;import org.junit.Test;import java.sql.Connection;import java.util.Properties;public class jdbcConn {//方式2@Testpublic void connect02() throws Exception {//使用反射加载Driver类,动态加载 , 更加地灵活 , 减少依赖性Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");Driver driver = (Driver)aClass.newInstance();String url = "jdbc:mysql://localhost:3306/hsp_db02";//将 用户名和密码 放入到 Properties对象中Properties properties = new Properties();// user 和 password 是规定好的 , 后面的值根据实际情况写properties.setProperty("user", "root");//用户properties.setProperty("password", "123456");//密码Connection connect = driver.connect(url, properties);System.out.println("方式2="+connect);}}
2.2.3方式3在方式2的基础上使用DriverManager替换Driver
经验总结扩展阅读
- 三伏贴是去医院还是推拿店好 推拿店的三伏贴和医院的有什么区别
- 精梳棉和100%棉的区别
- 古代风的雅称
- 商行和便利店的区别
- 杨梅和海鲜同食会中毒吗 食用杨梅的注意事项
- 买二手空调要注意什么
- 椒盐是胡椒粉和盐么
- 烧鸡和烤鸡的区别
- 沟通四大洋的海峡名称
- 联发科天玑1000plus和骁龙855哪个玩游戏好