日期:2014-05-20 浏览次数:20756 次
import java.sql.*; import java.io.*; public class JDBC { Connection con; Statement st; InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); public JDBC(){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println ("正在连接数据库....."); con = DriverManager.getConnection("jdbc:odbc:MyODBC","sa",""); st = con.createStatement(); System.out.println ("数据库连接成功."); }catch(ClassNotFoundException cnfe){ cnfe.printStackTrace(); }catch(SQLException sql){ sql.printStackTrace(); } } public void addbase() throws Exception{ System.out.println ("请输入ID:"); int id = Integer.parseInt(br.readLine()); System.out.println ("请输入姓名:"); String name = br.readLine(); System.out.println ("请输入年龄:"); int age = Integer.parseInt(br.readLine()); System.out.println ("请输入性别:"); String sex = br.readLine(); System.out.println (id+" "+name+" "+age+" "+sex);//输入英文或数字的话String可以正确显示,但是中文就 成了问号,比如:我输入"张三",输出的是"张",输入一个中文,就是问号 PreparedStatement ps = con.prepareStatement("insert into job values(?,?,?,?)"); ps.setInt(1,id); ps.setString(2,name); ps.setInt(3,age); ps.setString(4,sex); ps.executeUpdate(); } public void deletebase() throws Exception{ System.out.println ("请输入要删除的ID:"); int id = Integer.parseInt(br.readLine()); PreparedStatement ps = con.prepareStatement("delete from job where id = ?"); ps.setInt(1,id); ps.executeUpdate(); } public void selectbase() throws Exception{ ResultSet rs = st.executeQuery("select * from job"); while(rs.next()){ System.out.println ("学号:"+rs.getInt("id")); System.out.println ("姓名:"+rs.getString("name")); System.out.println ("年龄:"+rs.getInt("age")); System.out.println ("性别:"+rs.getString("sex")); System.out.println ("*****************************"); } } public void closes() throws Exception{ br.close(); isr.close(); con.close(); } public static void main(String[] args) { JDBC tmp = new JDBC(); try{ //tmp.addbase(); //tmp.deletebase(); tmp.selectbase(); tmp.closes(); }catch(ClassNotFoundException cnfe){ cnfe.printStackTrace(); }catch(SQLException sql){ sql.printStackTrace(); }catch(Exception ep){ ep.printStackTrace(); } } }
package test.input; import java.io.BufferedReader; import java.io.InputStreamReader; public class TestSystemIn { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); public void addbase() throws Exception { System.out.println("请输入ID:"); int id = Integer.parseInt(br.readLine()); System.out.println("请输入姓名:"); String name = br.readLine(); System.out.println("请输入年龄:"); int age = Integer.parseInt(br.readLine()); System.out.println("请输入性别:"); String sex = br.readLine(); System.out.println(id + " " + name + " " + age + " " + sex);// 我这里输出正常 } public static void main(String[] args) throws Exception { TestSystemIn o = new TestSystemIn(); o.addbase(); } }