I am using Java and Mysql for a Program, I am Using a Script File in order to restore a Databsae.
Under Java I am Executing a command:under bin: mysql -u root -proot test< c:\test.mysql
It is not running while If I run it under cmd line it will execute properly and restore the database.
Is anybody there who knows.. why it happens..
Whats the problem, why its not running if i run it under Java environment.
EXACT SYNTAX:
I m Using Process P= runtime.getRunTime().exec(FilePath)
where FilePath Variable is having value: mysql -u root -proot test< c:\test.mysql
I am Using Windiws environment. while if I run the FilePath in CmdLine, it will give the perfect reesult.
Highly thankful or help.
I had the same problem!
Actually the only thing that I could make work (on Windows, havent tested other platforms) is using batch files:
here is the code:
public class MysqlDatabase {
private int BUFFER = 10485760;
private String host, port, user, password, db;
public MysqlDatabase(String host, String port, String user, String password, String db) {
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.db = db;
}
public boolean restoreDatabase(String filepath) throws Exception {
String comando = "mysql " + db + " --host=" + host + " --port=" + port
+ " --user=" + user + " --password=" + password
+ " < " + filepath;
File f = new File("restore.bat");
FileOutputStream fos = new FileOutputStream(f);
fos.write(comando.getBytes());
fos.close();
Process run = Runtime.getRuntime().exec("cmd /C start restore.bat ");
return true;
}
public String getFull() throws Exception {
Process run = Runtime.getRuntime().exec(
"mysqldump --host=" + host + " --port=" + port
+ " --user=" + user + " --password=" + password
+ " --opt "
+ "" + db);
InputStream in = run.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder temp = new StringBuilder();
int count;
char[] cbuf = new char[BUFFER];
while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
temp.append(cbuf, 0, count);
}
br.close();
in.close();
return temp.toString();
}}
I think we need some more information. As long as the paths are set up the same, if it will run from the command line, it should run the same from Runtime.exec(). What errors do you see?
Try setting the commend up in a script so you can echo the paths and the command output to a file to look at later. In UNIX that would look like
LOGFILE=my.log
echo $PATH > $LOGFILE
env >> $LOGFILE
mysql -u root -proot test< c:\test.mysql >> $LOGFILE 2>&1
It looks like you're using Windows, so I don't know how to set of the command file exactly this way; what's important is to make sure you're sending the error output of the mysql commend to the file.
Related
I am creating a project where I want to do auto update by downloading update data from the server (FIRMWARE and SPIFFS update), I did it and it works, but I have a little problem because the device configuration (wifi password, ssid etc.) is saved on the SPIFFS partition.
But as you can guess, updating SPIFFS with a .bin image will remove the file from the configuration. I came up with the idea to load the configuration into RAM before updating SPIFFS and then overwrite the already updated configuration file with the data previously loaded into RAM after the update.
But the problem is with the solution that after restarting the board, the configuration file has the update data, not the RAM overwritten. But when the board is booted 5-10 times, the actual configuration data read from RAM suddenly appears in the configuration file.
It is a bit problematic and it shouldn't be a solution that should be included in the software, because it may not always be loaded on all board.
Does anyone know how effectively you can overwrite the update data before restarting the board?
I will add that I use the default memory partitioning layout:
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x140000,
app1, app, ota_1, 0x150000,0x140000,
spiffs, data, spiffs, 0x290000,0x170000,
This is code:
void makeUpdate(String host, String bin, int command = 0)
{
WiFiClientSecure client;
client.setCACert(github_cert);
long contentLength = 0;
bool isValidContentType = false;
Serial.println("Connecting to: " + String(host));
if (client.connect(host.c_str(), PORT)){
Serial.println("Fetching Bin: " + String(bin));
client.print(String("GET ") + bin + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Cache-Control: no-cache\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0){
if (millis() - timeout > 5000){
Serial.println("Client Timeout !");
client.stop();
return;
}
}
while (client.available()){
String line = client.readStringUntil('\n');
line.trim();
if (!line.length()) break;
if (line.startsWith("HTTP/1.1")){
if (line.indexOf("200") < 0){
Serial.println("Got a non 200 status code from server. Exiting OTA Update.");
break;
}
}
if (line.startsWith("Content-Length: ")){
contentLength = atol((this->getHeaderValue(line, "Content-Length: ")).c_str());
Serial.println("Got " + String(contentLength) + " bytes from server");
}
if (line.startsWith("Content-Type: ")){
String contentType = this->getHeaderValue(line, "Content-Type: ");
Serial.println("Got " + contentType + " payload.");
if (contentType == "application/octet-stream") isValidContentType = true;
}
}
}
else Serial.println("Connection to " + String(host) + " failed. Please check your setup");
Serial.println("contentLength : " + String(contentLength) + ", isValidContentType : " + String(isValidContentType));
String configFileSave = "";
if (contentLength && isValidContentType){
//*************** This is read config file **************************
if (command == U_SPIFFS){
Serial.printf("Reading config file: %s\r\n", CONFIG_FILE);
File file = SPIFFS.open(CONFIG_FILE);
if (!file || file.isDirectory()){
Serial.println("======Failed to open config file======");
return;
}
configFileSave = file.readString();
file.close();
Serial.println("--Configuration file reading complete--");
}
//*************** This is read config file **************************
bool canBegin = Update.begin(contentLength, command, LED_BUILTIN, HIGH);
if (canBegin){
Serial.println("Begin OTA. This may take 2 - 5 mins to complete. Things might be quite for a while.. Patience!");
size_t written = Update.writeStream(client);
if (written == contentLength) Serial.println("Written : " + String(written) + " successfully");
else Serial.println("Written only : " + String(written) + "/" + String(contentLength) + ". Retry?");
if (Update.end()){
Serial.println("OTA done!");
if (Update.isFinished()){
//*************** This is write config file **************************
if (command == U_SPIFFS){
Serial.printf("Writing config file: %s\r\n", CONFIG_FILE);
File file = SPIFFS.open(CONFIG_FILE, FILE_WRITE);
if (!file || file.isDirectory()){
Serial.println("======Failed to open config file======");
return;
}
if (!file.println(configFileSave)){
Serial.println("======Failed to write data to config file======");
return;
}
file.close();
Serial.println("--Completed writing data to the configuration file");
File f = SPIFFS.open(CONFIG_FILE, FILE_READ);
if (!f || f.isDirectory()){
Serial.println("======Failed to open config file======");
return;
}
String configFile = f.readString();
Serial.print("===Config File: ");
Serial.println(configFile);
f.close();
}
//*************** This is write config file **************************
Serial.println("Update successfully completed. Rebooting.");
// ESP.restart();
}
else Serial.println("Update not finished? Something went wrong!");
}
else Serial.println("Error Occurred. Error #: " + String(Update.getError()));
}
else{
Serial.println("Not enough space to begin OTA");
client.flush();
}
}
else{
Serial.println("There was no content in the response");
client.flush();
}
}
I am creating a login/sign up form using C++ and MySQL on Visual Studio 2019, despite the fact that the sign up works and actually stores the information the user inputs into the databse. While logging into the application, even if the password is correct, always the "username or password is incorrect!\n try again..." is always outputted when running the application. I haven't tried much because I am not even able to see the error in the first place.
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
try
{
String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=database";
MySqlConnection^ con = gcnew MySqlConnection(constr);
String^ password = textBox8->Text;
String^ username = textBox1->Text;
MySqlCommand^ cmd = gcnew MySqlCommand("select * from register_table where Username='" + username + "' and Password='" + password + "';", con);
MySqlDataReader^ dr;
con->Open();
try
{
dr = cmd->ExecuteReader();
int count = 0;
while (dr->Read())
{
count += 1;
}
if (count == 1)
{
MessageBox::Show("Login successful, Congratulations...");
}
else
{
MessageBox::Show("username or password is incorrect!\n try again...");
}
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
con->Close();
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
}
For anyone interested, after debugging the application, I saw that for some reason it confused the password and username. So I just switched their places and it worked, in this way that is:
MySqlCommand^ cmd = gcnew MySqlCommand("select * from register_table where Username='" + password + "' and Password='" + username + "';", con);
Kind of weird, but hey it works!
am trying to add shapefile data to postgis using c#
string path = browse_path.Text;
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
Process p = new Process();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
p = Process.Start(startInfo);
string chgdir = #"chdir " + #"C:\Program Files\PostgreSQL\9.4\bin\";
p.StandardInput.WriteLine(chgdir);
string pass = #"set PGPASSWORD=postgres";
p.StandardInput.WriteLine(pass);
string cmd = #"shp2pgsql -I -s 4326 " + path + " public.states | psql -U postgres -d postgres";
p.StandardInput.WriteLine(cmd);
p.WaitForExit();
p.Close();`
and for waiting almost 7-8 mins its not working. my shp file is 160 kb only.. but the command is working fine if i run it in the cmd rather then using code..
This is a function I wrote to import shapefiles to PG. It uses Nuget packages CliWrap and Npgsql and I just copied shp2pgsql and its dependencies to a project folder 'Tools' so it can be run on a machine that doesn't have PostgreSQL installed. Its a bit messy and you might need to add error handling but it worked for my needs.
public async static Task<bool> OutputSHPtoPSGLAsync(string shpfile, string host, string user, string pwd, string db, string schema = "public", bool dropIfExists = true, string table = "[SHPNAME]")
{
FileInfo shp = new FileInfo(shpfile);
if (!shp.Exists) return false;
if (table == "[SHPNAME]") table = Path.GetFileNameWithoutExtension(shpfile).ToLower();
string args = string.Format("{0} {1}.{2}", shpfile, schema, table);
Command cli = Cli.Wrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"tools\shp2pgsql.exe")).WithArguments(args);
ExecutionResult eo = await cli.ExecuteAsync();
string sql = eo.StandardOutput;
if (dropIfExists) sql = sql.Replace("CREATE TABLE", string.Format("DROP TABLE IF EXISTS \"{0}\".\"{1}\";\r\nCREATE TABLE", schema, table));
string constring = string.Format("Host={0};Username={1};Password={2};Database={3}", host, user, pwd, db);
using (NpgsqlConnection connection = new NpgsqlConnection(constring))
{
connection.Open();
new NpgsqlCommand(sql, connection).ExecuteNonQuery();
}
return true;
}
I was looking at NetTopologySuite which has type definitions compatible with Npgsql and PostGIS but its all still pre-release and couldn't be bothered working it out.
I try to execute following code using gcc test.c -o test.o -ldbi command.
#include <stdio.h>
#include <dbi/dbi.h>
int main() {
dbi_conn conn;
dbi_result result;
double threshold = 4.333333;
unsigned int idnumber;
const char *fullname;
dbi_initialize(NULL);
conn = dbi_conn_new("mysql");
dbi_conn_set_option(conn, "host", "localhost");
dbi_conn_set_option(conn, "username", "root");
dbi_conn_set_option(conn, "password", "root123");
dbi_conn_set_option(conn, "dbname", "test");
dbi_conn_set_option(conn, "encoding", "UTF-8");
if (dbi_conn_connect(conn) < 0) {
printf("Could not connect. Please check the option settings\n");
}
else {
result = dbi_conn_queryf(conn, "SELECT id, name FROM users");
if (result) {
while (dbi_result_next_row(result)) {
idnumber = dbi_result_get_uint(result, "id");
fullname = dbi_result_get_string(result, "name");
printf("%i. %s\n", idnumber, fullname);
}
dbi_result_free(result);
}
dbi_conn_close(conn);
}
dbi_shutdown();
return 0;
}
I have only 'Could not connect. Please check the option settings' as result always.
I can connect my data base using following command with password root123
mysql -h localhost -u root -p
And I can used test database in command line.
Please help me. What are the possible issues?
It has worked after install libdbd-mysql. Now I had install following packages.
libdbd-mysql
libdbi0
libdbi0-dev
Thank all of you.
Ok I am having real difficulty solving this. I'm trying to connect to a mysql database from a zend application and i receive the following error:
Message: No database adapter present
I have checked and double checked the connection credentials and they should be fine. The code should be fine too as it works ok in the development environment. If I deliberately change the password to be incorrect in the development environment, I get exactly the same error, which leads me to believe that maybe this is the case, despite my checking!
Any thoughts would be very welcome. If there's nothing obviously wrong here then maybe I need to look at the server/db/php settings?
Thanks!
Bootstrap code:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initPlaceholders(){
Zend_Session::start();
$this->bootstrap('View');
$view = $this->getResource('View');
$view->doctype('XHTML1_STRICT');
// Set the initial stylesheet:
$view->headLink()->appendStylesheet('/css/global.css');
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('Pog_');
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH . '/controllers/helpers',
'Application_Controller_Action_Helper_');
}
}
Config file:
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.view.helperPath.View_Helper = APPLICATION_PATH "/views/helpers"
database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user
database.params.password = password
database.params.dbname = test
DB connection helper:
/**
* Constructor: initialize plugin loader
*
* #return void
*/
public function __construct()
{
try{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$dbAdapter = Zend_Db::factory($config->database);
$dbAdapter->getConnection();
$this->connection = $dbAdapter;
} catch (Zend_Db_Adapter_Exception $e) {
echo 'perhaps a failed login credential, or perhaps the RDBMS is not running';
} catch (Zend_Exception $e) {
echo 'perhaps factory() failed to load the specified Adapter class';
}
}
public function getDbConnection(){
return $this->connection;
}
}
Index:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run();
Define your database as a resource
resources.db.adapter = pdo_mysql
resources.db.params.host = localhost
resources.db.params.username = user
resources.db.params.password = password
resources.db.params.dbname = test
In your main files you then need to do nothing but initiate a query without having to worry about assigning the database fvrom your config - its done in the inside, the DB resource is always chosen as the default adapter for your database transactions