您的位置:首页 > 编程语言 > Java开发

java jdbc数据库操作

2016-05-14 15:24 393 查看
(数据库连接,插入操作,查询操作 )


不管多少先写一下,发泄一下心情!好坑啊!

这样写不行:

sta.executeUpdate("insert into employee values(number,name,'1980-10-11',salary)");

这样写就对了:(原来不是函数传值,而是传的字符串,要符合sql语句的规范)

sta.executeUpdate("insert into employee values('"+number+"','"+name+"','1980-10-11','"+salary+"')");

练习第一段代码(补)

package mysql_practice;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class testTwo {
public static void main(String args[]) {
Connection con;
Statement sta;
ResultSet rs;
PreparedStatement preparedStatement;
String sql = null;
try {
// 使用Class.forName(String).newInstance()方法
// 将真正的Connector/J驱动类生成实例。
// 生成驱动类实例
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println(e);
}

try {
// 连接URL为 jdbc:mysql//服务器地址/数据库名 ,
// 后面的2个参数分别是登陆用户名和密码
// MySQL在高版本需要指明是否进行SSL连接。
// 加载驱动类生成的实例
con = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/javalecture?characterEncoding=utf8&useSSL=true",
"root", "12345678");
// 调用方法createStatement()创建SQL语句对象
sta = con.createStatement();
// 使用Statement类的executeQuery()方法执行SQL语句,
// 返回结果使用ResultSet对象存储
rs = sta.executeQuery("select * from employee");
sql = "insert into employee(number, name, birthday, salary) values(?,?,?,?)";
preparedStatement =  con.prepareStatement(sql);
String number = new String();
String name = new String();
Date date;
double salary;

while (rs.next()) {
number = rs.getString(1);
name = rs.getString(2);
date = rs.getDate(3);
salary = rs.getDouble(4);
System.out.printf("%-4s", number);
System.out.printf("%-6s", name);
System.out.printf("%-15s", date);
System.out.printf("%6s\n", salary);
}

Scanner input = new Scanner(System.in);
while (true) {
System.out.println("请输入number,输入000结束!");
number = input.next();

if (number.contains("000"))
break;
System.out.println("请输入name");
name = input.next();
System.out.println("请输入date");
String s = input.next();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// java.util.Date utildate = sdf.parse(s);
System.out.println("请输入salary");
salary = input.nextDouble();
sta.executeUpdate("insert into employee values('"+number+"','"+name+"','1980-10-11','"+salary+"')");
//				sta.executeUpdate("insert into employee values(number,name,'1980-10-11',salary)");
}
con.close();

} catch (SQLException e) {
System.out.println(e);
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 jdbc java