Skip to content

Instantly share code, notes, and snippets.

@nickname55
Created February 17, 2022 17:17
Show Gist options
  • Save nickname55/516c0d61c347cd088cd99fae71f6b215 to your computer and use it in GitHub Desktop.
Save nickname55/516c0d61c347cd088cd99fae71f6b215 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>java-examples</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
</dependencies>
</project>
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.sql.*;
public class SqlToCsv {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
try (CSVWriter writer = new CSVWriter(new FileWriter("filename.csv"))) {
Boolean includeHeaders = true;
Statement statement = null;
ResultSet myResultSet = null;
try {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://db-mysql-jlkjlkghjkn.com:25560/defaultdb?allowPublicKeyRetrieval=true&useSSL=false", "admin", "admin");
if (connection != null) {
statement = connection.createStatement();
myResultSet = statement.executeQuery("SELECT * FROM stat_online;");
writer.writeAll(myResultSet, includeHeaders);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment