m0_60957578
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class inserta {
public static void main(String[] args) { //TODO Auto-generated method stub
try{
Class.forName("com.mysql.cj.jdbc.Driver");//加载数据库驱动
System.out.println("加载数据库驱动成功");
String url="jdbc:mysql://localhost:3306/bookdatabase?characterEnding=UFT-8";//声明数据库test的url
Connection conn=DriverManager.getConnection(url,"root","root");
System.out.println("连接数据库驱动成功");
//生成一条SQL语句
String sql="insert into booklist(id,name,author,price,publisher) values(?,?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);//创建一个Statement对象
Statement stmt = conn.createStatement(); //创建Statement对象
Statement stmt2 = conn.createStatement();
String sql2 = "select * from booklist"; //要执行的SQL
ResultSet rs = stmt2.executeQuery(sql2);//创建数据对象
System.out.println("id"+"t"+"name"+"t"+"author"+"t"+"price"+"t"+"publisher");
while (rs.next()){
System.out.print(rs.getInt(1) + "t");
System.out.print(rs.getString(2) + "t");
System.out.print(rs.getString(3) + "t");
System.out.print(rs.getFloat(4) + "t");
System.out.print(rs.getString(5) + "t");
System.out.println();
}
ps.setString(1,"7");//为sql语句中第一个问号赋值
ps.setString(2,"洛克王国");//为sql语句中第二个问号赋值
ps.setString(3,"图图");//为sql语句第三个问号赋值
ps.setFloat(4,66.6f);//为sql语句的第四个问号赋值
ps.setString(5,"淮安逆天出版社");
ps.executeUpdate();//执行sql语句
System.out.println("插入后:");
Statement stmt3 = conn.createStatement();
System.out.println("成功连接到数据库!");
String sql3 = "select * from booklist"; //要执行的SQL
ResultSet rs1 = stmt3.executeQuery(sql3);//创建数据对象
System.out.println("id"+"t"+"name"+"t"+"author"+"t"+"price"+"t"+"publisher");
while (rs1.next()){
System.out.print(rs1.getInt(1) + "t");
System.out.print(rs1.getString(2) + "t");
System.out.print(rs1.getString(3) + "t");
System.out.print(rs1.getFloat(4) + "t");
System.out.print(rs1.getString(5) + "t");
System.out.println();
}
conn.close();//关闭数据库连接对象
System.out.println("关闭数据库连接对象");
} catch(ClassNotFoundException e) { //TODO Auto-generated catch block
e.printStackTrace();
}
catch(SQLException e) { //TODO Auto-generated catch block
e.printStackTrace();
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)