Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java PostgreSQL:如何将文本文件中的行插入数据库表?_Java_Database_Postgresql_Insert Into - Fatal编程技术网

Java PostgreSQL:如何将文本文件中的行插入数据库表?

Java PostgreSQL:如何将文本文件中的行插入数据库表?,java,database,postgresql,insert-into,Java,Database,Postgresql,Insert Into,如何从包含[x,y,z]格式的多个URL的文本文件中读取和插入行,例如: 1谷歌com(用标签隔开) 到数据库表中(无需手动复制每一行) 我是编程新手 感谢您的时间和帮助,善良的先生们和夫人 import java.sql.*; import java.util.Scanner; import java.io.*; public class Database { public static Connection connectToDatabase(String user, Strin

如何从包含[x,y,z]格式的多个URL的文本文件中读取和插入行,例如:

1谷歌com(用标签隔开)

到数据库表中(无需手动复制每一行)

我是编程新手

感谢您的时间和帮助,善良的先生们和夫人

import java.sql.*;
import java.util.Scanner;
import java.io.*;

public class Database {

    public static Connection connectToDatabase(String user, String port, String database) {
        System.out.println("-------- PostgreSQL " + "JDBC Connection Testing ------------");
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {

            System.out.println("Where is your PostgreSQL JDBC Driver? " + "Include in your library path!");
            e.printStackTrace();
        }
        System.out.println("PostgreSQL JDBC Driver Registered!");

        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:" + port + "/" + database, user,
                    "doesn't matter!");
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
        }
        return connection;
    }

    public static ResultSet executeSelect(Connection connection, String query) {
        Statement st = null;
        try {
            st = connection.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

        ResultSet rs = null;
        try {
            rs = st.executeQuery(query);
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

        return rs;
    }

    public static void dropTable(Connection connection, String table) {
        Statement st = null;
        try {
            st = connection.createStatement();
            st.execute("DROP TABLE " + table);
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void createTable(Connection connection, String tableDescription) {
        Statement st = null;
        try {
            st = connection.createStatement();
            st.execute("CREATE TABLE " + tableDescription);
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static int insertIntoTableFromFile(Connection connection, String table, String file) {

        BufferedReader br = null;
        int numRows = 0;
        try {
            Statement st = connection.createStatement();
            String sCurrentLine, brokenLine[], composedLine = "";
            br = new BufferedReader(new FileReader(file));

            while ((sCurrentLine = br.readLine()) != null) {
                // Insert each line to the DB
                brokenLine = sCurrentLine.split(",");
                composedLine = "INSERT INTO dotcom VALUES (";
                int i;
                for (i = 0; i < brokenLine.length - 1; i++) {
                    composedLine += "'" + brokenLine[i] + "',";
                }
                composedLine += "'" + brokenLine[i] + "')";
                numRows = st.executeUpdate(composedLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return numRows;
    }

    public static void main(String[] argv) throws SQLException, FileNotFoundException {

        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your Username:");
        String user = input.next();
        System.out.println("Please enter your Port ID:");
        String port = input.next();
        String database = "test";

        Connection connection = connectToDatabase(user, port, database);

        Statement st = connection.createStatement();

        if (connection != null) {
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
            return;
        }
        // Now we're ready to work on the DB

        // read TopURLs file
        try {
            BufferedReader fileReader = new BufferedReader(new FileReader("TopURLs"));

            while (fileReader.readLine() != null) {

                st.execute("DROP TABLE IF EXISTS dotcom;");
                st.execute("CREATE TABLE dotcom (rank integer PRIMARY KEY, domainName varchar(128), domainType varchar(128));");
                //st.execute("INSERT INTO dotcom VALUES (fileReader.nextLine(), fileReader.nextLine(), fileReader.nextLine());");
                //st.execute("COPY dotcom FROM 'TopURLs' WITH DELIMITER as 'delimiter'");

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

        // connection is of type Connection (in JDBC)
        DatabaseMetaData dbm = connection.getMetaData();

        // check if table is there
        ResultSet tables = dbm.getTables(null, null, "table name", null);
        if (tables.next()) {
            System.out.println("Table exists");
        } else {
            System.out.println("Table does not exist");
        }

        // check if view is there?
        //"create view foo as select * from table;"
        //"select * from foo;"
        ResultSet views = dbm.getTables("catalog name", null, null, null);
        if (views.next()) {
            System.out.println("View exists");
        } else {
            System.out.println("View does not exist");
        }

        String query = "SELECT * FROM branch";
        ResultSet rs = executeSelect(connection, query);
        try {
            while (rs.next()) {
                System.out.print("Column 1 returned ");
                System.out.println(rs.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        rs.close();

        dropTable(connection, "dotcom");
        createTable(connection,
                "dotcom (id int primary key, name varchar(15), type varchar(15));");
        int rows = insertIntoTableFromFile(connection, "customer", "src/Table.txt");
        System.out.println(rows + " rows inserted.");
    }
}
import java.sql.*;
导入java.util.Scanner;
导入java.io.*;
公共类数据库{
公共静态连接connectToDatabase(字符串用户、字符串端口、字符串数据库){
System.out.println(“--PostgreSQL”+“JDBC连接测试------------”;
试一试{
Class.forName(“org.postgresql.Driver”);
}catch(classnotfounde异常){
println(“您的PostgreSQL JDBC驱动程序在哪里?”+“包含在您的库路径中!”);
e、 printStackTrace();
}
System.out.println(“PostgreSQL JDBC驱动程序已注册!”);
连接=空;
试一试{
connection=DriverManager.getConnection(“jdbc:postgresql://localhost:“+端口+”/“+数据库,用户,
“没关系!”;
}捕获(SQLE异常){
System.out.println(“连接失败!检查输出控制台”);
e、 printStackTrace();
}
回路连接;
}
公共静态结果集executeSelect(连接、字符串查询){
语句st=null;
试一试{
st=connection.createStatement();
}捕获(SQLE异常){
e、 printStackTrace();
返回null;
}
结果集rs=null;
试一试{
rs=st.executeQuery(查询);
圣克洛斯();
}捕获(SQLE异常){
e、 printStackTrace();
返回null;
}
返回rs;
}
公共静态void dropTable(连接、字符串表){
语句st=null;
试一试{
st=connection.createStatement();
st.execute(“升降台”+升降台);
圣克洛斯();
}捕获(SQLE异常){
e、 printStackTrace();
}
}
公共静态void createTable(连接、字符串表描述){
语句st=null;
试一试{
st=connection.createStatement();
st.execute(“创建表”+表描述);
圣克洛斯();
}捕获(SQLE异常){
e、 printStackTrace();
}
}

公共静态int insertIntoTableFromFile(连接、字符串表、字符串文件){ BufferedReader br=null; int numRows=0; 试一试{ 语句st=connection.createStatement(); 字符串sCurrentLine,brokenLine[],composedLine=“”; br=新的BufferedReader(新的文件读取器(文件)); 而((sCurrentLine=br.readLine())!=null){ //将每一行插入数据库 brokenLine=sCurrentLine.split(“,”); composedLine=“插入到互联网价值(”; int i; 对于(i=0;iStatement createStatement = null; PreparedStatement insertStatement = null; try { BufferedReader fileReader = new BufferedReader(new FileReader("TopURLs")); String line = null; createStatement = connection.createStatement(); createStatement.executeUpdate("CREATE TABLE dotcom (rank integer PRIMARY KEY, domainName varchar(128), domainType varchar(128))"); connection.setAutoCommit(false);//commit whole batch at the end insertStatement = connection.prepareStatement("INSERT INTO dotcom VALUES (?, ?, ?)"); while ( (line = fileReader.readLine()) != null) { line = fileReader.readLine(); String[] urls = line.split(" ");//space or any other delimiter that you're using insertStatement.setString(1, urls[0]); insertStatement.setString(2, urls[1]); insertStatement.setString(3, urls[2]); insertStatement.addBatch(); } insertStatement.executeBatch(); connection.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if(connection != null) { connection.setAutoCommit(true); } if(createStatement != null) { createStatement.close(); } if(insertStatement != null) { insertStatement.close(); } }