Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save BacLuc/86b204c567f43dffb20bcd2177c32c0a to your computer and use it in GitHub Desktop.
create db connection
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/f8734ef97696d270da5adb0e140eb454-master.iml" filepath="$PROJECT_DIR$/.idea/f8734ef97696d270da5adb0e140eb454-master.iml" />
</modules>
</component>
</project>
package com.company;
/**
* Created by lucius on 16.05.17.
*/
public class Config_sample {
public static String URL = "localhost";
public static String USERNAME = "username";
public static String PASSWORD = "password";
public static String DB_NAME = "mydb";
public static String PORTNUMBER = "3306";
}
package com.company;
import java.sql.*;
import java.util.Properties;
import static com.company.Config.*;
public class Main {
public static Connection getConnection() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", USERNAME);
connectionProps.put("password", PASSWORD);
conn = DriverManager.getConnection(
"jdbc:" + "mysql" + "://" +
URL +
":" + PORTNUMBER + "/"+DB_NAME,
connectionProps);
System.out.println("Connected to database");
return conn;
}
public static void main(String[] args) {
// write your code here
try (Connection conn = getConnection()) {
String query = "" +
"SHOW TABLES;";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("Result of "+query);
while(rs.next()){
System.out.println(rs.getString(1));
}
PreparedStatement preparedStatement = conn.prepareStatement(
"SELECT id,name,othervalue FROM test where id = ?"
);
preparedStatement.setInt(1,1);
rs.close();
rs = preparedStatement.executeQuery();
System.out.println("Result of select of test");
System.out.println("id\tname\tothervalue");
while(rs.next()){
System.out.println(String.format("%d\t%s\t%s", rs.getInt("id"), rs.getString(2), rs.getString(3)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment