📄 connectiontest.java
字号:
import java.sql.*;
import java.text.NumberFormat;
public class ConnectionTest
{
public static void main(String[] args)
{
NumberFormat cf = NumberFormat.getCurrencyInstance();
ResultSet movies = getMovies();
try
{
while (movies.next())
{
Movie m = getMovie(movies);
String msg = Integer.toString(m.year);
msg += ": " + m.title;
msg += " (" + cf.format(m.price) + ")";
System.out.println(msg);
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private static ResultSet getMovies()
{
Connection con = getConnection();
try
{
Statement s = con.createStatement();
String select = "Select title, year, price "
+ "from movie order by year";
ResultSet rows;
rows = s.executeQuery(select);
return rows;
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
return null;
}
private static Connection getConnection()
{
Connection con = null;
try
{
Class.forName("org.postgressql.Driver");
String url = "jdbc:postgresql://postgres.it.usyd.edu.au/jter3924";
String user = "jter3924";
String pw = "308074300";
con = DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
private static Movie getMovie(ResultSet movies)
{
try
{
String title = movies.getString("Title");
int year = movies.getInt("Year");
double price = movies.getDouble("Price");
return new Movie(title, year, price);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
return null;
}
private static class Movie
{
public String title;
public int year;
public double price;
public Movie(String title, int year, double price)
{
this.title = title;
this.year = year;
this.price = price;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -