JDBC,连接到mysql数据库

来源:互联网 发布:c语言if else嵌套 编辑:程序博客网 时间:2024/05/18 21:08

工具 Eclipse    

数据库管理软件Navicat

import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;import java.sql.ResultSet;import java.sql.SQLException;public class MySQLDemo{public static void main(String[] args){Connection conn = null;Statement stmt = null;ResultSet rs = null;String driver = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/www";//数据库表名String user = "root";String password = "123456";//String insertSql = "insert into students values('20162007','小白','16','女')";String deleteSql = "delete from students where name = '小明'";try{Class.forName(driver);conn = DriverManager.getConnection(url,user,password);System.out.println("数据库连接成功");//创建载体stmt = conn.createStatement();//创建结果集rs = stmt.executeQuery("select num,name,age,sex from students");while(rs.next()){System.out.println("学号:"+rs.getString(1)+"\t姓名:"+rs.getString(2)+"\t年龄:"+rs.getString(3)+"\t性别:"+rs.getString(4));}//删除数据stmt.executeUpdate(deleteSql);System.out.println("删除成功!");//执行添加SQL记录//int count1 = stmt.executeUpdate(insertSql);//System.out.println("添加了"+count1+"行记录");}catch(ClassNotFoundException e1){System.out.println("数据库连接失败!!!");e1.printStackTrace();}catch(SQLException e2){e2.printStackTrace();}finally{try{//关闭结果集if(rs != null){rs.close();}//关闭载体if(stmt != null){stmt.close();}//关闭连接if(conn != null){conn.close();}}catch(SQLException e){e.printStackTrace();}}}}