Dropping MySQL table with SparkSQL - mysql

I know that we can query or create a Mysql table from SparkSQL through the below commands.
val data = sqlContext.read.jdbc(urlstring, tablename, properties)
data.write.format("com.databricks.spark.csv").save(result_location)
val dataframe = sqlContext.read.json("users.json")
dataframe.write.jdbc(urlstring, table, properties)
Like that is there any way to drop a table ?

You can try a basic DROP operation with the JDBC driver :
val DB_URL: String = ???
val USER: String = ???
val PASS: String = ???
def dropTable(tableName: String) = {
import java.sql._;
var conn: Connection = null;
var stmt: Statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
println("Connected database successfully...");
println("Deleting table in given database...");
stmt = conn.createStatement();
val sql: String = s"DROP TABLE ${tableName} ";
stmt.executeUpdate(sql);
println(s"Table ${tableName} deleted in given database...");
} catch {
case e: Exception => println("exception caught: " + e);
} finally {
???
}
}
dropTable("test")
You can do that with Spark using JDBCUtils but this is quite straightforward.

You can have a look at the write mode method
dataframe.write.mode('overwrite').jdbc(urlstring, table, properties)
Overwrite mode means that when saving a DataFrame to a data source, if data/table already exists, existing data is expected to be overwritten by the contents of the DataFrame.
from: https://spark.apache.org/docs/latest/sql-data-sources-load-save-functions.html#save-modes
Also, you can put in the properties to truncate if you don't want to delete the definition too.
This is a JDBC writer-related option. When SaveMode.Overwrite is enabled. This option causes Spark to truncate an existing table instead of dropping and recreating it. This can be more efficient and prevents the table metadata (e.g., indices) from being removed. However, it will not work in some cases, such as when the new data has a different schema. It defaults to false. This option applies only to writing.
from: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html

Related

Very simple Slick query, get a single value

I'm trying to introduce slick into my code to replace some existing jdbc code.
First of all I'd like to use a scala worksheet to run a really simple query, I want to pass in an integer id, and get back a string uuid. This is the simplest method in the whole codebase.
As I understand I need to make a connection to the database, setup an action, and then run the action. I have the following code:
val db = Database.forURL("jdbc:mysql://mysql-dev.${URL}/${DB}?autoReconnect=true&characterEncoding=UTF-8",
driver = "com.mysql.jdbc.Driver", user = "${user}",password= "${pass}")
val getUUID = sql"""SELECT ${UUIDFIELD} from users u WHERE u.${IDFIELD} = ${Id}""".as[String]
val uuid:String = db.run(getUUID)
println(uuid)
I'm pretty sure I don't have the driver setup correctly in the Database.forURL call, but also the worksheet is complaining that the result of db.run is not a string. How do I get to the string UUID value?
The db.run method returns a Future[_] type. You should use Await for getting result from it.
val db = Database.forURL("jdbc:mysql://mysql-dev.${URL}/${DB}?autoReconnect=true&characterEncoding=UTF-8",
driver = "com.mysql.jdbc.Driver", user = "${user}",password= "${pass}")
val getUUID = sql"""SELECT ${UUIDFIELD} from users u WHERE u.${IDFIELD} = ${Id}""".as[String]
val uuidFuture:Future[String] = db.run(getUUID)
import scala.concurrent._
import scala.concurrent.duration._
val uuid:String = Await.result(uuidFuture, Duration.Inf)
println(uuid)

Is SchemaCrawler broken when using its API?

I am refering the doc in http://sualeh.github.io/SchemaCrawler/how-to.html#api
But I never get what I want. The tables returned is always empty.
final Connection connection = ... // Get a MYSQL connection;
final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
options.setSchemaInfoLevel(SchemaInfoLevelBuilder.maximum());
options.setTableInclusionRule(new IncludeAll());
options.setTableNamePattern("*");
final Catalog catalog = SchemaCrawlerUtility.getCatalog(connection, options);
for (final Schema schema: catalog.getSchemas())
{
Collection<Table> tables = catalog.getTables(schema);
//
// The size of tables is always 0
//
System.out.println(tables);
}
You should not set the table name pattern, so please remove the following line:
options.setTableNamePattern("*");
Sualeh Fatehi, SchemaCrawler

Load 3D model in Unity using Resource folder and Mysql

I want to load 3D model using Resource folder. I created an sql database to store the address. In this case I stored the file "deer-3ds" in folder "Models" and also save these information in a table named "modeladdress" in sql.
So please help me to correct my code. I know that it's 100% wrong but I dont know how to fix it. Thank you.
using UnityEngine;
using System.Collections;
using System;
using System.Data;
using Mono.Data.Sqlite;
public class addobject : MonoBehaviour {
// Use this for initialization
void Start () {
//GameObject deer=Instantiate(Resources.Load("deer-3d.bak",typeof(GameObject)))as GameObject;
// GameObject instance = Instantiate(Resources.Load("Models/deer-3ds", typeof(GameObject))) as GameObject;
string conn = "URI=file:" + Application.dataPath + "/modeladdress.s3db"; //Path to database.
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT ordinary,foldername, filename " + "FROM modeladdress";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read ()) {
int ordinary = reader.GetInt32 (0);
string foldername = reader.GetString (1);
string filename = reader.GetString (2);
string path = foldername + "/" + filename;
//Debug.Log( "value= "+value+" name ="+name+" random ="+ rand);
GameObject instance = Instantiate(Resources.Load(path, typeof(GameObject))) as GameObject;
instance.SetActive (true);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
// Update is called once per frame
void Update () {
// GameObject instance = Instantiate(Resources.Load("Models/deer-3ds", typeof(GameObject))) as GameObject;
// instance.SetActive (true);
}
}
First of all, you are using SQLite at your database management system, not MySQL. Second, the way you have written your query,
string sqlQuery = "SELECT ordinary,foldername, filename " + "FROM modeladdress";
Will return the ordinary, foldername, and filename for every model. You need to use a WHERE clause to specify precisely which model you want to use. Thus, you need some way to know which model you want to query from the database before you actually execute the query, and in that case, why even query a database? You're going to have to store some unique identifier anyway so a database solves nothing.
Now concerning the actual code you have written, it appears to be correct (i.e. it should be returning what you want). The problem must be that either your table is empty, your values that are returned are incorrect, or that the object is being instantiated in an incorrect location and thus you are thinking it's not working. If you want a more concrete answer you'll have to comment on this answer with the specific problem you are facing (i.e. what specifically is "wrong"?).

generic upper case search on postgres and mysql not working

I am trying to do an easy search on a table that can be on any kind of database. The following query is working an the most databases, but I cannot find a solution which works on mysql.
The tables in my database are generated by the active objects framework, so I cannot change the names or config of those instances.
Here is the query that works fine on all databases but MySQL:
select * from "AO_69D057_FILTER" where "SHARED" = true AND "CONTAINS_PROJECT" = true AND UPPER("FILTER_NAME") like UPPER('%pr%').
MySql is not able to use the table name in double quotes for some reason. If I use the unquoted table name it works on MySQL but not on Postgres. Postgres is converting the table name to lowercase because it is unquoted. AO is generating the table names in upper case.
I also tried to use an alias, but that can not work because of the evaluation hierarchy of the statement.
Any suggestions how to get rid of the table name problem?
By default double quotes are used to columns.
You can change it:
SET SQL_MODE=ANSI_QUOTES;
Here is the documentation about it:
http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
I had the same problem. I select the query according to the exception I get. In the first call of the db search, I try without quotes if it fails then I try with quotes. Then I set useQueryWithQuotes variable accordingly so that in future calls I do not need to check the exception. Below is the code snipped I am using.
private Boolean useQueryWithQuotes=null;
private final String queryWithQuotes = "\"OWNER\"=? or \"PRIVATE\"=?";
private final String queryWithoutQuotes = "OWNER=? or PRIVATE=?";
public Response getReports() {
List<ReportEntity> reports = null;
if(useQueryWithQuotes==null){
synchronized(this){
try {
reports = new ArrayList<ReportEntity>( Arrays.asList(ao.find(ReportEntity.class, Query.select().where(queryWithoutQuotes, getUserKey(), false))) );
useQueryWithQuotes = false;
} catch (net.java.ao.ActiveObjectsException e) {
log("exception:" + e);
log("trying query with quotes");
reports = new ArrayList<ReportEntity>( Arrays.asList(ao.find(ReportEntity.class, queryWithQuotes, getUserKey(), false)));
useQueryWithQuotes = true;
}
}
}else{
String query = useQueryWithQuotes ? queryWithQuotes : queryWithoutQuotes;
reports = new ArrayList<ReportEntity>( Arrays.asList(ao.find(ReportEntity.class, query, getUserKey(), false)));
}
...
}

How can I display data into my Jtextarea from my data base Mysql

I have problem when I try to display data(the result of a query) from my database mysql to my jTextarea, when I compile I have an error exception like:
SQL Exception: java.sql.SQLException: Can not issue SELECT via executeUpdate()
I have used a "select" query from my table where the name is the name written in my jTextFieldNom,this is my code, I hope that some one help me because I don't know how to resolve the problem, I 'm sure that my query is correct but I don't know where is the problem.
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
instruction = connexion.createStatement();
int rowsEffected = instruction.executeUpdate(SQL);
jTextArea1.append(rs.getString("description"));
}
...... //bloc catch
This line is executing a Select statement which is throwing the error.
int rowsEffected = instruction.executeUpdate(SQL);
You don't need this line because you aren't updating your database.
Also change the append to setText
jTextArea1.setText(rs.getString("description"));
Try this:
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
jTextArea1.setText(rs.getString("description"));
}