在java中怎么样把键盘输入到控制台的值保存到数据库里面,举个案例一定要有源代码

如题所述

用scanner获取键盘输入值然后在获取connection连接CRUD数据库追问

给举个简单的案列吧,亲,急需啊我,谢谢谢谢....

给举个简单的案列吧,亲,急需啊我,谢谢谢谢....

追答

上面的代码都可以

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-24

                           

//获取键盘输入值
Scanner s = new Scanner(System.in);
String str = s.nextLine();

//获取数据库连接
public Connection getConnection(){
  Connection conn = null ;
  try{
       //根据数据库不同,使用不同数据库驱动
       Class.forName("com.mysql.jdbc.Driver") ;
       //数据库连接地址,用户名,密码
       conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stud", 
               "root", "root") ;
       return conn ;


       e.printStackTrace() ;
   }
   return null ;
 }
 
 //插入接收的值
 String sql= "INSERT INTO tableName VALUES(?) ;    
 PreparedStatement preState = conn.prepareStatement(sql);    
 preState.setString(1, columnName); //字段名称
 ResultSet rs = preState.executeUpdate();    
 
 //最后记得关闭数据库连接,释放资源

本回答被提问者采纳
第2个回答  2013-09-24
package com.gengjw.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class ConsoleJdbc {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 如果有输入
        if (scan.hasNext()) {
            Connection conn = null;
            try {
                conn = getConn();
                PreparedStatement stat = conn.prepareStatement("insert tblDumy values(?)");
                // 从1开始设置参数,用控制台输入值
                stat.setString(1, scan.next());
                // 执行sql文
                int rowCount = stat.executeUpdate();
                // 返回受影响的记录数
                if (rowCount == 1) {
                    System.out.println("正确插入了。");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        // 关闭时异常,忽略
                    }
                }
            }
        }
    }
    /**
     * 
     * 取得数据库连接<br>
     * 
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private static Connection getConn() throws ClassNotFoundException, SQLException {
        // MySQL为例
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/objoa?useUnicode=true&characterEncoding=utf-8",
                "user", "passwd");
    }
}

本回答被网友采纳
第3个回答  2013-09-24
估计这位仁兄想要做黑软把。。。
相似回答