标签:
JDBC 模版
try {
class.forName( JDBC 驱动类);
1、加载JDBC 驱动
Class. forName("com.mysql.jdbc.Driver");
2、与数据库建立连接
connection con=DriverManager.getConnection(URL,数据库用户名,密码);
//URL 用来标识数据库
PreparedStatement pstmt=con.PreparedStatement("查询sql语句");
ResultSet rs=pstmt.executeQuery();
//执行SQL语句,并得到返回结果
while (rs.next()){
int x=rs.getint("a");
String s=rs.getString("b");
float f=rs.getFloat("c");
// 处理放回结果
}
rs.close();
pstmt.close();
con.close(); //关闭连接
//释放资源
}
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
try {
//1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2、建立连接
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/nyschool?CharacterEncoding=UTF-8","root","root");
//System.out.println("建立连接成功!!");
//3、创建 prepareStatement 接口并编译 sql语句
//pstmt=conn.prepareStatement("select * from student");
//执行删除
Scanner input=new Scanner(System.in);
//System.out.print("请输入要删除的学生学号:");
//int stuNo=input.nextInt();
//两种方法:
//方法1:String sql="DELETE FROM student WHERE stuNo="+stuNo;
//方法2:String sql="DELETE FROM student WHERE stuNo=7";
//执行添加
System.out.print("请输入添加的学员的编号:");
int stuNo=input.nextInt();
System.out.print("请输入添加学员的性别:");
String name=input.next();
System.out.print("请输入添加的地址:");
String phone=input.next();
//
String sql="INSERT INTO student VALUES (?,‘a2323‘,‘qq‘,?,1,?,‘江西南昌‘,SYSDATE(),‘qq.com‘)";
pstmt=conn.prepareStatement(sql); //预编译方式
//给占位符赋值
pstmt.setInt(1, stuNo);
pstmt.setString(2, name);
pstmt.setString(3, phone);
System.out.print("sql:"+sql);
//4、执行SQL语句,并得到返回结果
//rst=pstmt.executeQuery(); //执行查询
int num=pstmt.executeUpdate(); //执行增删改
//5、处理返回结果
if(num>0){
System.out.println("\n添加成功!");
}else{
System.out.println("\n添加失败!");
}
while (rs.next()){
int x=rs.getint("a");
String s=rs.getString("b");
float f=rs.getFloat("c");
// 处理放回结果
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
标签:
原文地址:http://www.cnblogs.com/hanxiaowen/p/5601808.html