Home > Net >  Is their a way to export a MYSQL Table directly in java
Is their a way to export a MYSQL Table directly in java

Time:12-11

Before anything, thanks you, english isn't my native language and i'm sorry for any mitsake i would make. If my question is stupid, i'm sorry too.

I'm making an application, that allow to export some tables in different format csv: no problem, xls: same, however SQL require more than putting some ",", Using PHPMyAdmin i noticed i can export the db directly in SQL, is their a way to directly get this sql code? I said in java as the app is in java, but ofc it might required something else and that's not an issue.

Anyways, thanks for going through my messy explanation, have a nice day.

CodePudding user response:

You can run your .sql file with ScriptRunner.

Here is the way you can use it.

Connection conn=getConnection();//some method to get a Connection
ScriptRunner runner=new ScriptRunner(conn, false, false);
InputStreamReader reader = new InputStreamReader(new 
FileInputStream("foo.sql"));
runner.runScript(reader);
reader.close();
conn.close();

CodePudding user response:

you can use mysqldump command this can be used via Runtime.getRuntime().exec()

String command = "mysqldump -u username -p password database_name table_name";

Process p = Runtime.getRuntime().exec(command);

$command = "mysqldump -u username -p password database_name table_name";

system($command);

or else u can go for mysqli approach

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database_name");

// Check for errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Get the data from the table
$result = $mysqli->query("SELECT * FROM table_name");

// Loop through the data and write it to a file or format it as desired
while ($row = $result->fetch_assoc()) {
    // Write the data to a file or format it as desired
}

// Close the connection
$mysqli->close();
  • Related