jdbc简单的连接

来源:互联网 发布:windows安装ant 编辑:程序博客网 时间:2024/06/05 12:48

1.创建一张表(JDBC的DDL操作

①首先先在lib放入mysql驱动

②然后

public class DDlAndExceptionTest {//1.创建一张表@Testpublic void DDlAndExceptionTest() throws Exception {String sql="CREATE TABLE `t_student` (`id` bigint(20) PRIMARY KEY AUTO_INCREMENT,`name` varchar(20),`age` int(11))";//1.加载注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接对象Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytext", "root", "root");//3.创建/获取语句对象Statement st=conn.createStatement();//4.执行sql语句st.executeUpdate(sql);//5.释放资源st.close();conn.close();}}
③数据库的表


2.JDBC的DML操作

①代码

public class DMLTest {//需求1:向t_student表中,插入:西风吹雪 32@Testpublic void DMLTestInsert() throws Exception {String sql="INSERT INTO t_student (name,age) VALUES('西风吹雪',32)";//1:加载注册驱动Class.forName("com.mysql.jdbc.Driver");//2:获取连接对象Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytext", "root", "root");//3:创建/获取语句Statement st=conn.createStatement();//4:执行sqlint i=st.executeUpdate(sql);System.out.println(i);//5:释放资源st.close();conn.close();}//需求2:把id为2的名字改为乔峰,34岁@Testpublic void testUpdate() throws Exception {String sql="UPDATE t_student SET name='乔峰',age=35 WHERE id='2'";//1.加载注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接对象Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytext", "root", "root");//3.创建/获取语句Statement st=conn.createStatement();//4.执行语句int i=st.executeUpdate(sql);//5.释放资源st.close();conn.close();}//需要3:删除id为2的学生@Testpublic void testDelete() throws Exception{String sql = "DELETE FROM t_student WHERE id='2'";//1.加载注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接对象Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytext", "root", "root");//3.创建/获取语句Statement st=conn.createStatement();//4.执行语句int i=st.executeUpdate(sql);//5.释放资源st.close();conn.close();}}




0 0
原创粉丝点击