小妹留学僧~关于java的问题,异国他乡向各位同胞大大求助啊,求助求助!
本帖最后由 thistf 于 2012-11-14 02:07:08 编辑 作业基本就是一个利用jdbc连接数据库并且操作数据的编程作业..因为之前没有接触过java,所以都是摸索着来的,这个是我实现的能够读配置文件连接数据库,并且把一个文件的内容导入到数据库中.代码贴在下面,本来我这个程序直接java db 就可以运行了, 可是老师要求运行程序的命令行是java -classpath .;mysql-connector-java-5.1.18-bin.jar Populate db.properties student.txt vehicle.txt route.txt stop.txt zone.txt
的格式
因为没有学过java,都是找类似资料来实现的,这个要求找不到相应的资料只能求助各位大大了~拜托拜托了!
还有就是我的代码只是实现了读一个文件进去,老师这个要求是一下子读5个文件进去,分别存到不同的表里,而且要求要用 JDBC PreparedStatement construct来实现重复的语句...请问这个该怎么修改代码啊
祝路过各位大大一生平安啊!!!
package practice;
/*test*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
public static void main(String[]args){
String s;
int t = 0;
String[] sa=new String[5];
List data = new ArrayList();
try{
BufferedReader in =new BufferedReader(new FileReader("src/db.properties"));
while((s=in.readLine())!=null){
sa[t] =s.substring(0);
t++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
/*connect the DB*/
String url = "jdbc:mysql://"+sa[0]+":"+sa[1]+"/"+sa[2];
String username = sa[3];
String password = sa[4];
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
}catch (SQLException e1) {
e1.printStackTrace();
}
/*put data in DB*/
File file = new File("D:\\HW3\\HW3\\data\\student.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String line = null;
String sql = null;
String info[] = null;
String path = file.getAbsolutePath();//得到选择文件的全路径
String fileName = path.substring(path.lastIndexOf("\")+1, path.lastIndexOf("."));//取得所选文件名
String province = fileName.substring(0,fileName.length()-2);
String cardType = fileName.substring(fileName.length()-2);
try {
while((line = br.readLine())!= null){
info = line.split(",");
sql = sql = "insert into cc(A,B,C)values('"+ info[0] +"','"+info[1]+"','"+info[2]+"')";
stmt.executeUpdate(sql);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
CREATE TABLE `route` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`r1` VARCHAR(255) DEFAULT NULL,
`r2` VARCHAR(255) DEFAULT NULL,
`r3` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `student` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`st1` VARCHAR(255) DEFAULT NULL,
`st2` VARCHAR(255) DEFAULT NULL,
`st3` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
CREATE TABLE `vehicle` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`v1` VARCHAR(255) DEFAULT NULL,
`v2` VARCHAR(255) DEFAULT NULL,
`v3` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
CREATE TABLE `zone` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`z1` VARCHAR(255) DEFAULT NULL,
`z2` VARCHAR(255) DEFAULT NULL,
`z3` VARCHAR(255) DEFAULT NULL,
`z4` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
CREATE TABLE `stop` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`s1` VARCHAR(255) DEFAULT NULL,
`s2` VARCHAR(255) DEFAULT NULL,
`s3` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
r1-1,r1-2,r1-3
r2-1,r2-2,r2-3
s1-1,s1-2,s1-3
s2-1,s2-2,s2-3
st1-1,st1-2,st1-3
st2-1,st2-2,st2-3
v1-1,v1-2,v1-3
v2-1,v2-2,v2-3
z1-1,z1-2,z1-3,z1-4
z2-1,z2-2,z2-3,z2-4
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Populate {
public static void main(String[] args) {
PreparedStatement pstm=null;
Connection conn = null;
try {
File propertiesFile=new File(args[0]);
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(propertiesFile);
prop.load(fis);
String username=prop.getProperty("username");
String password=prop.getProperty("password");
String url = prop.getProperty("url");
File studentFile=new File(args[1]);
File vehicleFile=new File(args[2]);
File routeFile=new File(args[3]);
File stopFile=new File(args[4]);
File zoneFile=new File(args[5]);
List<File> fileList=new ArrayList<File>();
fileList.add(studentFile);
fileList.add(routeFile);
fileList.add(stopFile);
fileList.add(vehicleFile);
fileList.add(zoneFile);
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
String fileds="";
String routeFields="r1,r2,r3";
String stopFields="s1,s2,s3";
String studentFields="st1,st2,st3";
String vehicleFields="v1,v2,v3";
String zoneFields="z1,z2,z3,z4";
for (File file : fileList) {
String fileName=file.getName();
fileName = fileName.replace(".txt", "");
System.out.println("fileName..."+fileName);
FileReader fr = new FileReader(file);
BufferedReader bufferedReader=new BufferedReader (fr);
String str="";
String[] values=null;
//通过文件名称来判断这个表的fileds
if(fileName.equals("route")){
fileds=routeFields;
}else if(fileName.equals("stop")){
fileds=stopFields;
}else if(fileName.equals("student")){
fileds=studentFields;
}else if(fileName.equals("zone")){
fileds=zoneFields;
}else if(fileName.equals("vehicle")){
fileds=vehicleFields;
}
String[] s=fileds.split(",");
int k=s.length;
String val="";
for(int i =0 ;i<k;i++ ){
if(i<k-1){
val+=" ? , ";
}else{
val+=" ? ";
}
}
while ((str=bufferedReader.readLine())!=null) {
values=str.split(",");
String sql="insert into "+fileName+" ( "+ fileds + " ) values ( " +val+ " )";
System.out.println(sql);
pstm =conn.prepareStatement(sql);
for (int i = 1; i <= k; i++) {
System.out.println("set value.."+values[i-1]);
pstm.setString(i, values[i-1]);//values数组下标从0开始,当pstm设置第一个?的时候 values则是第[0]个
}
pstm.execute();
}
bufferedReader.close();
fr.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
pstm.close();
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
package DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtils {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("Driver fails to load...");
}
}
public static Connection getConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=GBK","root","root");
} catch(SQLException e){
System.out.println("link failed to database...");
}
return conn;
}
public static PreparedStatement getPstmt(Connection conn, String sql) {
PreparedStatement ps = null;
try{
ps = conn.prepareStatement(sql);
}catch(SQLException e){
System.out.println("预处理失败");
}
return ps;
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn){
if(rs != null){
try{
rs.close();
}catch(SQLException e){
System.out.println("关闭异常");
}
}
if(ps != null){
try{
ps.close();
}catch(SQLException e){
System.out.println("关闭异常");
}
}
if(conn != null){
try{
conn.close();
}catch(SQLException e){
System.out.println("关闭异常");
}
}
}
}
楼主 你上面这句话什么意思哦。 写死了额。 这个不用我解释,自己看得懂吧 还有 这个参数是arg0[] 传进来的 按你的导师的要求。你应该是从传入的字符串数据的第一个位置获取这个值。
[其他解释]
哇塞 中文这么好,哪国的?有图有答案
[其他解释]
应该检查args数组的内容。。。。。
[其他解释]
既然可以导入一个文件那就依葫芦画瓢,将其他的文件也导入
[其他解释]
既然可以导入一个文件那其他的文件也应该会导入了吧
[其他解释]
conn = DBUtils.getConnection();
String sql = "select * from users where lastname = ?"; // 这里用问号
st = conn.prepareStatement(sql);
st.setString(1,name); // 这里将问号赋值
rs = st.executeQuery();
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
public class db {
public static void main(String[]args){
/*read the properties*/
String s;
int t = 0;
String[] sa=new String[5];
List data = new ArrayList();
try{
BufferedReader in =new BufferedReader(new FileReader(args[0]));
while((s=in.readLine())!=null){
sa[t] =s.substring(0);
t++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
/*connect the DB*/
String url = "jdbc:mysql://"+sa[0]+":"+sa[1]+"/"+sa[2];
String username = sa[3];
String password = sa[4];
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = DriverManager.getConnection(url, username, password);
}catch (SQLException e1) {
e1.printStackTrace();
}
/*put data in DB*/
File file = new File(args[1]);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String line = null;
String sql = null;
String info[] = null;
String path = file.getAbsolutePath();//得到选择文件的全路径
String fileName = path.substring(path.lastIndexOf("\")+1, path.lastIndexOf("."));//取得所选文件名
String province = fileName.substring(0,fileName.length()-2);
String cardType = fileName.substring(fileName.length()-2);
try {
while((line = br.readLine())!= null){
info = line.split(",");
sql = "insert into cc(A,B,C)values('"+ info[0] +"','"+info[1]+"','"+info[2]+"')";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
CREATE TABLE `student`(
`id` INT NOT NULL AUTO_INCREMENT ,
`filename` VARCHAR(255) , `content` VARCHAR(255) , PRIMARY KEY (`id`) );
CREATE TABLE `route`(
`id` INT NOT NULL AUTO_INCREMENT ,
`filename` VARCHAR(255) , `content` VARCHAR(255) , PRIMARY KEY (`id`) );
CREATE TABLE `vehicle`(
`id` INT NOT NULL AUTO_INCREMENT ,
`filename` VARCHAR(255) , `content` VARCHAR(255) , PRIMARY KEY (`id`) );
CREATE TABLE `stop`(
`id` INT NOT NULL AUTO_INCREMENT ,
`filename` VARCHAR(255) , `content` VARCHAR(255) , PRIMARY KEY (`id`) );
CREATE TABLE `zone`(
`id` INT NOT NULL AUTO_INCREMENT ,
`filename` VARCHAR(255) , `content` VARCHAR(255) , PRIMARY KEY (`id`) );
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/users";
String username = "root";
String password = "root";
Connection conn = null;
PreparedStatement stmt = null;
File studentFile=new File("D:/dbtest/student.txt");
File routeFile=new File("D:/dbtest/route.txt");
File stopFile=new File("D:/dbtest/stop.txt");
File vehicleFile=new File("D:/dbtest/vehicle.txt");
File zoneFile=new File("D:/dbtest/zone.txt");
List<File> fileList=new ArrayList<File>();
fileList.add(studentFile);
fileList.add(routeFile);
fileList.add(stopFile);
fileList.add(vehicleFile);
fileList.add(zoneFile);
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstm=null;
for (File file : fileList) {
String fileName=file.getName();
fileName = fileName.replace(".txt", "");
System.out.println("fileName..."+fileName);
FileReader fr = new FileReader(file);
BufferedReader bufferedReader=new BufferedReader (fr);
String content=bufferedReader.readLine();
String sql="insert into "+fileName+" (filename,content) values (? , ?)";
pstm =conn.prepareStatement(sql);
pstm.setString(1, fileName);
pstm.setString(2, content);
pstm.execute();
bufferedReader.close();
fr.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
PreparedStatement pstm=null;
Connection conn = null;
try {
String url = "jdbc:mysql://localhost:3306/users";
String username = "root";
String password = "root";
File studentFile=new File("D:/dbtest/student.txt");
File routeFile=new File("D:/dbtest/route.txt");
File stopFile=new File("D:/dbtest/stop.txt");
File vehicleFile=new File("D:/dbtest/vehicle.txt");
File zoneFile=new File("D:/dbtest/zone.txt");
List<File> fileList=new ArrayList<File>();
fileList.add(studentFile);
fileList.add(routeFile);
fileList.add(stopFile);
fileList.add(vehicleFile);
fileList.add(zoneFile);
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
for (File file : fileList) {
String fileName=file.getName();
fileName = fileName.replace(".txt", "");
System.out.println("fileName..."+fileName);
FileReader fr = new FileReader(file);
BufferedReader bufferedReader=new BufferedReader (fr);
String content=bufferedReader.readLine();
String sql="insert into "+fileName+" (filename,content) values (? , ?)";
pstm =conn.prepareStatement(sql);
pstm.setString(1, fileName);
pstm.setString(2, content);
pstm.execute();
bufferedReader.close();
fr.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
pstm.close();
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Populate{
public static void main(String[] args) {
PreparedStatement pstm=null;
Connection conn = null;
try {
File propertiesFile=new File(args[0]);
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(propertiesFile);
prop.load(fis);
String username=prop.getProperty("username");
String password=prop.getProperty("password");
String url = prop.getProperty("url");
File studentFile=new File(args[1]);
File vehicleFile=new File(args[2]);
File routeFile=new File(args[3]);
File stopFile=new File(args[4]);
File zoneFile=new File(args[5]);
List<File> fileList=new ArrayList<File>();
fileList.add(studentFile);
fileList.add(routeFile);
fileList.add(stopFile);
fileList.add(vehicleFile);
fileList.add(zoneFile);
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
for (File file : fileList) {
String fileName=file.getName();
fileName = fileName.replace(".txt", "");
System.out.println("fileName..."+fileName);
FileReader fr = new FileReader(file);
BufferedReader bufferedReader=new BufferedReader (fr);
String content=bufferedReader.readLine();
String sql="insert into "+fileName+" (filename,content) values (? , ?)";
pstm =conn.prepareStatement(sql);
pstm.setString(1, fileName);
pstm.setString(2, content);
pstm.execute();
bufferedReader.close();
fr.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
pstm.close();
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
while((line = br.readLine())!= null){
info = line.split(",");
sql = "insert into cc(Student,Co,La)values('"+ info[0] +"','"+info[1]+"','"+info[2]+"')";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
}r1,11,34.031811,-118.290025,34.031839,-118.285539,34.0304,-118.283342
r2,6,34.021592,-118.290083,34.023989,-118.288633,34.022975,-118.287014,34.022292,-118.284772,34.021056,-118.286961,34.020275,-118.287928
r3,7,34.022292,-118.284772,34.022975,-118.287014,34.023989,-118.288633,34.027061,-118.289869,34.029575,-118.289417,34.028975,-118.286039,34.026828,-118.281994
r4,8,34.021056,-118.286961,34.022369,-118.281581,34.022292,-118.284772,34.022975,-118.287014,34.021056,-118.286961,34.020275,-118.287928,34.019303,-118.289136,34.019478,-118.286425
create table route (
RouteID VARCHAR(20) PRIMARY KEY,
Num int(20),
rlocation LineString NOT NULL,
SPATIAL INDEX(rlocation)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
package com.mysql.jdbc
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// ~ Static fields/initializers
// --------------------------------------------- //
// Register ourselves with the DriverManager
//
static {
t ry {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
// ~ Constructors
// -----------------------
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException
* if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}