I just started taking my first steps in SQL.
I downloaded and installed XAMPP 1.8.3-3, and also downloaded the JDBC driver and wrote this code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class TestSQL {
public static void main(String[] args) {
Connection connection=null;
try {
MysqlDataSource ds=new MysqlConnectionPoolDataSource();
ds.setServerName("localhost");
connection=ds.getConnection("root", "");
Statement statement=connection.createStatement();
statement.execute("CREATE DATABASE my_database;");
statement.execute("USE my_database;");
statement.execute("CREATE TABLE my_table (" +
"private_name VARCHAR(10)," +
"last_name VARCHAR(10)," +
"age INT" +
");");
statement.execute("INSERT INTO my_table" +
"(private_name,last_name,age)" +
"VALUES " +
"('Ariel','Menashe',29)");
statement.execute("INSERT INTO my_table" +
"(private_name,last_name,age)" +
"VALUES " +
"('Aviad','Ganon',28)");
statement.execute("INSERT INTO my_table" +
"(private_name,last_name,age)" +
"VALUES " +
"('Oren','Vanunu',30)");
ResultSet rs=statement.executeQuery("SELECT * FROM my_table");
while (rs.next()) {
System.out.println("Mr. "+rs.getString("last_name")+", "+rs.getInt("age"));
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This code will compile and run, but my question is, how do I write code in SQL without Java? Can I run SQL commands through the terminal independently somehow?
Sure you can. If you have the MySQL command line client installed, you can start it up in a terminal and run any SQL command you like. Type this in your terminal:
mysql databasename -h host -u username -p
It will ask for the password interactively. If your database is on the same server as the client, you can leave off the -h host
part.