public class mysql {
static{
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e ){
throw new RuntimeException(e);
}
}
public static void main(String [] args)throws ClassNotFoundException{
String driver ="com.mysql.jdbc.Driver";
String connStr = "jdbc:mysql://localhost:3306/stu";
String user="root";
String pwd ="123";
Connection conn = null;
Statement stmt= null;
ResultSet result = null;
try{
conn=DriverManager.getConnection(connStr,user,pwd);
stmt = conn.createStatement();
stmt.execute("use stu");
stmt.executeUpdate("insert into tb1(name,age)values('lili',20)");
result=stmt.executeQuery("select * from tb1");
while(result.next()){
System.out.println(result.getString(1));
System.out.println(result.getString(2));
System.out.println(result.getString(3));
}
result.close();
stmt.close();
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
把mysql的jar包导入到工程中
1.加载数据库驱动 Class.forName(com.myslq.jdbc.Driver);
2.创建连接 conn=DriverManager.getConnection(connStr,user,pwd);
3.执行sql语句 stmt = conn.createStatement();
stmt.executeUpdate("insert into tb1(name,age)values('lili',20)");
4.处理resultset
ResultSet result = null;
while(result.next()){
System.out.println(result.getString(1));
System.out.println(result.getString(2));
System.out.println(result.getString(3));
}
5.关闭(释放资源) result.close();
stmt.close();
conn.close();