这里有个要死记硬背的点,在类的名称后要加throws Exception,为啥,不知道。我懂得太少,以后或许能有机会知道。
package javaee1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcDemo{
private static String jdbcurl="jdbc:mysql://localhost:3306/test"; //这个是数据库的名称,端口
private static String name="root"; //这个是进入数据库的账户名
private static String password="666666"; //这个是进入数据库的密码
private static String jdbcname="com.mysql.jdbc.Driver"; //这个是连接数据库JDBC的驱动名称
public static void connection_text()throws Exception{
Class.forName(jdbcname); //加载驱动
System.out.println("驱动加载成功");
Connection con=DriverManager.getConnection(jdbcurl, name, password); //连接数据库
System.out.println("数据库连接成功");
con.close(); //关闭数据库
System.out.println("数据库关闭");
System.out.println('\n');
}
public static void select(String sql)throws Exception{
Class.forName(jdbcname);
Connection con=DriverManager.getConnection(jdbcurl, name, password);
///select开始
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet result=pstmt.executeQuery();
while(result.next())
{
String usernumbers=result.getString("usernumber");
String userpassword=result.getString("userpassword");
System.out.println(usernumbers+" "+userpassword);
}
System.out.println('\n');
con.close();
}
public static void insert_update_delete(String sql)throws Exception{
Class.forName(jdbcname);
Connection con=DriverManager.getConnection(jdbcurl, name, password);
///select开始
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.executeUpdate(); //删除就是这样,要用新的函数,而且查询代码不能写在下面,必须自己写查询函数,不然会报错。
con.close();
}
public static void main(String[] args)throws Exception {
String sql1="select * from user;";
String sql2="INSERT INTO USER VALUES(3,3);";
String sql3="DELETE FROM USER WHERE usernumber='666';";
String sql4="update user set usernumber='666',userpassword='666' where usernumber=3";
connection_text();
insert_update_delete(sql2); //插入
select(sql1);
insert_update_delete(sql4); //更新
select(sql1);
insert_update_delete(sql3); //删除
select(sql1);
}
}