用scanner获取键盘输入值然后在获取connection连接CRUD数据库
//获取键盘输入值
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();
//最后记得关闭数据库连接,释放资源
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) {
// 关闭时异常,忽略
}
}
}
}
}
/**
*
* 取得数据库连接
*
* @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");
}
}
估计这位仁兄想要做黑软把。。。