package news;
import java.sql.*;
public class ConnectMySqi {
public static void main(String[] args) {
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名young
String url = "jdbc:mysql://localhost:3306/young";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "root";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
String name = null;
String pwd = null;
PreparedStatement psql;
//预处理添加数据,其中有两个参数--“?”
psql = con.prepareStatement("insert into submit (name,pwd) "+ "values(?,?)");
psql.setString(1, "haha"); //设置参数1,name
psql.setString(2, "789");
/*//预处理更新(修改)数据
psql = con.prepareStatement("update submit set pwd = ? where name = ?");
` psql.setFloat(1,);
psql.setString(2,"王刚");
//预处理删除数据
psql = con.prepareStatement("delete from submit where name = ?");
psql.setFloat(1, 4500);*/
psql.executeUpdate(); //执行更新
//psql.close();
String sql = "select * from submit";
//3.ResultSet类,用来存放获取的结果集!!
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println("姓名" + "\t" + "密码");
System.out.println("-----------------");
while(rs.next()){
//获取stuname这列数据
name = rs.getString("用户名");
//获取stuid这列数据
pwd = rs.getString("密码");
//输出结果
System.out.println(name + "\t" + pwd);
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
}