此代码连接Mongodb和Mysql数据库。 mysql表thing(String)
和qty(int)
中有两个字段。我希望通过创建一个名为Names的对象类,使用string和int作为字段成员,然后使用它ArrayList,以与mongodb中的string和int相同的格式显示。我在行号93和94(在方法sqldbRead stock_list.add(....)
中)得到一个错误,因为我没有使用完美的格式,或者可能是代码中存在一些不同的错误。几个小时都无法解决这个问题。任何帮助将非常感谢!谢谢。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mysql.jdbc.Statement;
public class connect {
// this opens and inserts data into SQL database, takes columns variables( string, int)
public void sqldbInsert(String thing, int qty) throws ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Creating a connection");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","Testuser","");
System.out.println("Getting access to the database...");
}
catch(SQLException e){
System.err.println(e.getErrorCode()+" :"+e.getSQLState()+" :"+e.getMessage());
if(e.getErrorCode()==1049){
//create database here with its own try catch block
try{
//Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/","Testuser","");
Statement stmt = (Statement) con.createStatement();
String sql = "CREATE DATABASE test";
stmt.executeUpdate(sql);
System.out.println("Database created successfully");
} catch(SQLException e1){
System.err.println(e1.getErrorCode()+" :"+e1.getSQLState()+" :"+e1.getMessage());
}
try{
//Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","Testuser","");
System.out.println("Inserting values into the table");
PreparedStatement stmt = con.prepareStatement("INSERT INTO DETAILS (thing,qty)VALUES(?,?)");
stmt.setString(1, thing);
stmt.setInt(2, qty);
stmt.executeUpdate();
stmt.close();
con.close();
System.out.println("It's working!!");
}
catch(SQLException e1){
e1.printStackTrace();
}
}
}
}
// also open , and reads the sql table, using specific select statement using qty field
public void sqldbRead() throws SQLException, ClassNotFoundException{
// open, sql select, and close
//returns array of objects
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","Testuser","");
PreparedStatement statement = con.prepareStatement("select thing,qty from things where qty > 4");
ResultSet result = statement.executeQuery();
ArrayList<Names> stock_list = new ArrayList<Names>();
while(result.next()){
stock_list.add(result.getString(1));
stock_list.add(result.getInt(2));
}
Names[] stockArr = new Names[stock_list.size()];
for(Names s : stockArr)
System.out.println(s);
mongodbInsert(stockArr);
con.close();
}
// open mongo db, gets a array of objects, and inserts as Field:value pairs
public void mongodbInsert(Names[]s){
// open, insert collection into a known collection, close
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "First" );
System.out.println("Connect to database successfully");
try{
DBCollection coll = db.getCollection("begin");
System.out.println("Collection created successfully");
for(int i=0;i<s.length-1;i++){
BasicDBObject doc = new BasicDBObject().append(s[i].toString(),s[i+1]);
coll.insert(doc);
i++;
}
System.out.println("Document inserted successfully");
}catch(Exception e){
System.err.print(e.getMessage()+"Collection not found");
}
}catch(Exception e){
System.err.print(e.getMessage()+"Not connected to the database");
}
}
// read out specific mongodb document, takes string , int ( fieldname:value)
public void mongodbRead(){
// open, find, close
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "First" );
System.out.println("Connect to database successfully");
try{
DBCollection coll = db.getCollection("begin");
System.out.println("Collection created successfully");
Set<String> colls = db.getCollectionNames();
for (String s1 : colls) {
System.out.println(s1);
}
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("chair", "11");
DBCursor cursor = coll.find(whereQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}
catch(Exception e){
System.err.print(e.getMessage()+"Collection not found");
}
} catch(Exception e){
System.err.print(e.getMessage()+"Not connected to the database");
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException{
connect conn = new connect();
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string and a value to insert into the database");
String s = scan.next();
int i = scan.nextInt();
conn.sqldbInsert(s,i);
conn.sqldbRead();
conn.mongodbRead();
}
}
和Names类是:
public class Names {
private int qty;
private String name;
public Names(int qty, String name) {
this.qty = qty;
this.name = name;
}
public int getId() {
return this.qty;
}
public String getName() {
return this.name;
}
}
答案 0 :(得分:0)
stock_list.add()需要一个Names对象,你传递一个String和一个Integer。 试试
stock_list.add(new Names(result.getInt(), result.getString()); // give result.x() the right parameters
你也会在接下来的行中有一个bug,就像你在哪里创建一个新的数组,但是你把它留空并去找
for(Names s : stockArr)
这里stockArr的大小合适,但它是空的
for(Names s : stock_list)
这可以工作或者在你进入循环之前你可以调用列表上的数组函数我现在无法检查它但是我觉得它就像
stock_list.toArray();