c# console application backup mysql - mysql

I try to use this code as a console application so that I can back up mydatabase automatics
I am not sure what wrong with it
static void Main(string[] args)
{
try
{
DateTime backupTime = DateTime.Now;
int year = backupTime.Year;
int month = backupTime.Month;
int day = backupTime.Day;
int hour = backupTime.Hour;
int minute = backupTime.Minute;
int second = backupTime.Second;
int ms = backupTime.Millisecond;
String tmestr = backupTime.ToString();
tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
StreamWriter file = new StreamWriter(tmestr);
ProcessStartInfo proc = new ProcessStartInfo();
string cmd = string.Format(#"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
proc.FileName = "mysqldump";
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = true;
proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";
proc.UseShellExecute = false;
Process p = Process.Start(proc);
string res;
res = p.StandardOutput.ReadToEnd();
file.WriteLine(res);
p.WaitForExit();
file.Close();
}
catch (IOException ex)
{
MessageBox.Show("Disk full or other IO error , unable to backup!");
}
}

Since I'm not sure what kind of error you're geting, atleast this could be changed.
string cmd = string.Format(#"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
Later you commented it should be -u root -p smartdb > testdb.sql";
except the above, is missing the space after the -u so I'd change it to:
string cmd = string.Format(#"-u {0} -p {1} -h {2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");

Why are you creating a StreamWriter and trying to get the output of mysqldump, Why not just tell mysqldump to write to the backup file itself?
string cmd = string.Format(#"-u{0} -p{1} -h{2} {3} > ""{4}"";",
"root", "", "localhost", "dbfile", tmestr);

for starters i would change how you're outputting the information. You're essentially opening a file so you can redirect the backup utility's output to that file. The > in your process call is for that very purpose. Just change your "backup.sql" parameter to tmestr.
Also, because the output is already being redirected to a file, your process won't have anything to return. But because we're now having it dump to the correct path, this should be irrelevant.
One final change, add a space between your -u{0} so it's -u {0}. And the same with -h{2}.
In summary:
remove StreamWriter and all variables associated to it
modify the String.Format in your process arguments to use `tmestr
add spaces in your cmd variable for -u&-h
And you should be good-to-go (assuming it's not a problem with locating the mysqldump executable.

Related

unable to read hash from json file

This is part of my code for creating and logging into accounts in my game, I have cut out the acquisition of the username and password from the user and have just kept the password hashing and file read/writing
##CREATE ACCOUNT##
#Encrypt password
newPswdEnc = hashlib.sha512()
newPswd = bytes(newPswd, "ascii")
newPswdEnc.update(newPswd)
newPswdEnc = str(newPswdEnc.digest()).replace("\\", ".")
#Assemble and place in file
newLogin = {"Username":newUsnm,"Pswd":newPswdEnc,"Highscore":0}
with open("Users.json", "r+") as file:
data = json.load(file)
##DOES SOME EXTRA VALIDATION TO PREVENT DUPLICATE USERNAMES##
data["Logins"].append(newLogin)
with open("Users.json", "w+") as file:
json.dump(data. file, indent = 5)
##LOGIN##
#Encrypt password
pswdEnc = hashlib.sha512()
pswd = bytes(pswd, "ascii")
pswdEnc.update(pswd)
pswdEnc = str(pswdEnc.digest()).replace("\\", ".")
#CHECK USERNAME AND PASSWORD
with open("Users.json", "r") as file:
data = json.load(file)
for i in range(0, len(data["Logins"])):
if data["Logins"][i]["Username"] == usnm and data["Logins"][i]["Pswd"] == pswd:
loggedIn = True
##Logins.json##
{
"Logins": [
{
"Username": "ADMIN",
"Pswd": b'#.x8b.x90.xe6.xe28-.xda.xfa.xdc5&k/.xa9.xa3q.xfb9b.xb6u.xcc.xab.x1bU82.x1fF.x90p.xd0.xf3v/).xb2.x1a.xc7.xadw..xb6.xbd).x9d.t.xf8.xe7]8.xed.x8bpg.x96]]_&.xeb.xc3.xf5',
"Highscore": 0
}
],
}
When attempting to sign in with the correct password I get this error:
Expecting value: line 5 column 24 (char 90)
which appears to be the b character at the start of the hash
Problem with reading was solved by removing my filter for backslashes however I am now experiencing issues with the password comparison as whilst in another program I have put both hashes in variables and validated them. This program is refusing to do so.

How to connect to a web service that returns JSON in LUA

I am beginner in LUA. I have written the following code in lua file that mysql proxy run with it.
function read_query(packet)
if string.byte(packet) == proxy.COM_QUERY then
local command = string.lower(packet)
if string.find(command, "select") ~= nil and string.find(string.lower(packet), "from") ~= nil then
local socket = require('socket')
local conn, err = socket.connect('localhost', 5050)
print(conn, err)
proxy.response.type = proxy.MYSQLD_PACKET_OK
//proxy.response.resultset get json from web service (url)
proxy.response.resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_INT, name = "id", },
},
rows = {
{ 9001 }
}
}
return proxy.PROXY_SEND_RESULT
end
end
end
I want to connect to the web service on Port 5050 that return the JSON file and save the json that it returns in the proxy.response.resultset.
Another question, How can i add socket module. I paste files like following image
socket module files
but give an error : can not find /socket/core.lua.
local socket = require('socket')
You are using luasocket and it comes as a mix of lua (socket.lua) and binary (socket/core.so) files. You need to set (if it's not set already) to point to .so files; something like this may work: package.cpath=package.cpath..';./?.so'

c++ Mysql, can not close a Mysql connection

I have a function that receives parameters (schema name, column name etc) and updates a Mysql table, the problem is that when I use two Mysql commands inside this function (below), one to set the schema and one to update the table, the Close connection command at the end `(conDataBase3->Close();) does not work.
I am checking the number of open connections in the Mysql console (SHOW FULLPROCESSLIST) before and after running the function. any solutions or explanations? thanks
int simple_1::update_table_with_value(gcroot<String^ > schema, gcroot<String^ > table_name, int numerator, gcroot<String^ > field_to_update, double value_to_update)
{
gcroot<MySqlConnection^ > conDataBase3;
conDataBase3 = gcnew MySqlConnection(constring);
conDataBase3->Open();
try{
String ^ schema_name = "Use " + schema + " ;";
MySqlCommand ^cmdDataBase3 = gcnew MySqlCommand(schema_name, conDataBase3);
MySqlCommand ^cmdDataBase4 = gcnew MySqlCommand(schema_name, conDataBase3);
cmdDataBase3->ExecuteNonQuery();
String ^ temp1 = "UPDATE ";
String ^ temp2 = table_name;
String ^ temp3 = " SET ";
String ^ temp4 = field_to_update;
String ^ temp6 = "=(#value1) WHERE numerator = (#value2)";
String ^ temp8 = temp1 + temp2 + temp3 + temp4 + temp6;
// end of the writing part
cmdDataBase4 = gcnew MySqlCommand(temp8, conDataBase3);
cmdDataBase4->Parameters->AddWithValue("#value1", value_to_update);
cmdDataBase4->Parameters->AddWithValue("#value2", numerator);
cmdDataBase4->Prepare();
cmdDataBase4->ExecuteNonQuery();
}//try
catch (Exception^ ex)
{
System::Windows::Forms::MessageBox::Show(ex->Message);
}
conDataBase3->Close();
int answer = 0;
return (answer);
}
ok found the answer, I needed to disable the pooling option otherwise closing the connection still keeps the socket open..
found it here: http://bugs.mysql.com/bug.php?id=24138 see the last 2 lines.
The way to disable the pooling :
http://www.connectionstrings.com/mysql-connector-net-mysqlconnection/disable-connection-pooling/

Play - Execute an sql statement without writing the database configuration in application.conf

I am writing a scala application using the Playframework. I don't want to write the database configuration in the application.conf file. Instead I have a function similar to the one given below. I want to send the configuration parameters as arguments of a function. Then I want create a connection and execute the statement. BTW, the database is a mysql database.
def run_sql(sql: String, host: String, user: String, pass: String, port: String, dbname: String): Unit = {
// **** create the connection ****
DB.withConnection {
conn =>
{
val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
try {
statement.execute(sql)
}
catch {
case e: Exception => Logger.warn("Error executing DML %s. %s".format(sql, e.getMessage))
}
}
}
}
Is it possible? If so then how? I hope I have made my question clear. If you have any confusion please ask. Thanks in advance.
// **** create the connection ****
here we can write
val driver = Play.current.configuration.getString("rds.driver").getOrElse("")
val host = Play.current.configuration.getString("rds.host").getOrElse("")
val port = Play.current.configuration.getString("rds.port").getOrElse("")
val user = Play.current.configuration.getString("rds.user").getOrElse("")
val password = Play.current.configuration.getString("rds.password").getOrElse("")
val url = "mysql://" + user + ":" + password + "#" + host + ":" + port + "/" + dbname
// there's probably a better way to do this
Class.forName(driver)
val connection: Connection = DriverManager.getConnection(url, user, password)

Jdbc and MySql not wanting to play nicely together

I have been working on a java application that has a connection to a mysql database. I can connect and run queries but when I try to take a string and run it as a sql query I get this error.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO usageData (`COMID`,`Year`,`Month`,`kwhr`,`co2`)
VALUES ('15650', '2' at line 3
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583)
Bellow is the code that I'm using to connect to the database
public static void main(String[] args) throws Exception {
String dbms = "mysql";
String serverName = "localhost";
String portNumber = "8889";
String DBName = "ConnectDatabase";
String user = "root";
String password = "root";
ArrayList<Integer> yearList = new ArrayList<Integer>();
ArrayList<CustomerRecord> customerRecordList = getCustomerRecords(args[0], yearList);
ArrayList<ClimateRecord> climateRecordList = getClimateRecords(args[1]);
StringBuffer buf = new StringBuffer();
for (CustomerRecord record : customerRecordList) {
buf.append(customerRecord2SQL(record));
}
for (int i = (climateRecordList.size() - 1); i >= 0; i--) {
//for (ClimateRecord record : climateRecordList) {
ClimateRecord record = climateRecordList.get(i);
buf.append(climateRecord2SQL(record));
}
buf.append(cityStats(dbms,serverName,portNumber,DBName,user,password));
buf.append(zipStats(dbms,serverName,portNumber,DBName,user,password));
System.out.println(buf.toString());
//here is the code to go ahead and update the database
Connection con = null;
con = DriverManager.getConnection("jdbc:" + dbms + "://" + serverName + ":" + portNumber + "/" + DBName + "?user="+user+"&password=" + password);
Statement stmt = con.createStatement();
stmt.executeUpdate(buf.toString());
BufferedWriter out = new BufferedWriter(new FileWriter(args[2]));
out.write(buf.toString());
out.close();
}
This is not a connection issue. It means that something is wrong with your SQL statement. Try copying the statement as is and executing it directly in the database. See what is wrong and then correct it in the Java code.
I notice that the single quotes around the field names look fancy. That might be a problem.
Here's what was happening and what everyone else failed to realize. JDBC will not do more than one query at a time I was trying to run several million queries contained in a string buffer which wouldn't work.
Your query should be 'INSERT INTO usageData VALUES (COMID,Year,Month,kwhr,co2);
and btw COMID,year...what are these..?? and why fancy quotes...??